Java Field 详解

一.主要方法

getType(): 获取属性声明时类型对象(返回class对象)

getGenericType() : 返回属性的泛型类型

getName() : 获取属性声明时名字

getAnnotations() : 获得这个属性上所有的注释

getModifiers() : 获取属性的修饰

isEnumConstant() : 判断这个属性是否是枚举类

isSynthetic() : 判断这个属性是否是 复合类

get(Object obj) : 取得obj对象这个Field上的值

set(Object obj, Object value) : 向obj对象的这个Field设置新值value

Field类中最常用的是get(Object obj)和set(Object obj, Object value)这两个方法,所以这两个方法是最重要的。

getType() 和 getGenericType()的区别 :

1.首先是返回的类型不一样,一个是Class对象一个是Type接口

2.如果属性是一个泛型,从getType()只能得到这个属性的接口类型。但从getGenericType()能得到这个属性接口的泛型类型。

isEnumConstant()isSynthetic()

对象中如果有属性是枚举类或复合类,用这两个方法返回的值并不是我们想象的true而是false。其实这两个方法是对编译生成的才有效。

二.试验代码

package test.fortest;

import static java.lang.System.out;

import java.lang.reflect.Field;

import javassist.Modifier;
import test.model.Role;

public class FieldTest {
	enum Color {
		Blue,
		Red
	}
	
	class Inner {
	}
	
	public static void main(String args[]) {
		Role role = new Role();
		role.setId("role1");
		role.setUserId("user1");
		role.setRoleName("Role 1");
		
		Field idField =  getDeclaredField(role.getClass(), "id");
		Field childrenField =  getDeclaredField(role.getClass(), "children");
		Field roleTypeField =  getDeclaredField(role.getClass(), "roleType");
		Field userField =  getDeclaredField(role.getClass(), "user");
		
		//获取属性声明时类型对象(返回class对象)
		System.out.println(idField.getType());
		//返回属性声的Type类型
		System.out.println(idField.getGenericType());
		//如果属性是一个泛型,从getType只能得到这个属性的接口类型
		System.out.println(childrenField.getType());
		//如果属性是一个参数化类型,从getGenericType还能得到这个泛型的参数类型
		System.out.println(childrenField.getGenericType());
		//获取属性声明时名字
		System.out.println(idField.getName());
		//获得这个属性上所有的注释
		System.out.println(idField.getAnnotations().length);
		//获取属性的修饰
		System.out.println(Modifier.toString(idField.getModifiers()));
		
		//判断这个属性是否是枚举类
		System.out.println(roleTypeField.isEnumConstant());
		//判断这个属性是否是 复合类
		System.out.println(userField.isSynthetic());
		//FieldTest$Color是Color枚举类编译后的名字。
		isSyntheticOrEnumConstant("test.fortest.FieldTest$Color");
		//FieldTest$Inner是Inner类编译后的名字。
		isSyntheticOrEnumConstant("test.fortest.FieldTest$Inner");
		try {
			//取得对象这个Field上的值
			System.out.println(idField.get(role));
			//向对象的这个Field重新设置值
			idField.set(role, "role2");
			System.out.println(idField.get(role));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
	}
	
	public static Field getDeclaredField(final Class cla, final String fieldName) {
		for (Class superClass = cla; superClass != null; superClass = superClass.getSuperclass()) {
			try {
				return superClass.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
//				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static void isSyntheticOrEnumConstant (String completePackageName) {
		try {
			Class<?> c = Class.forName(completePackageName);
			Field[] flds = c.getDeclaredFields(); 
			for (Field f : flds) {  
				out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n",
						c.getName() + ":" + f.getName(), f.isSynthetic(), f.isEnumConstant());  
		    }  
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	}
}

结果:

class java.lang.String
class java.lang.String
interface java.util.List
java.util.List<test.model.User>
id
5
public
false
false
test.fortest.FieldTest$Color:Blue [ synthetic=false enum_constant=true  ]
test.fortest.FieldTest$Color:Red [ synthetic=false enum_constant=true  ]
test.fortest.FieldTest$Color:ENUM$VALUES [ synthetic=true  enum_constant=false ]
test.fortest.FieldTest$Inner:this$0 [ synthetic=true  enum_constant=false ]
role1
role2



三.用到的类

package test.model;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Table;

import test.enu.RoleType;

@Entity
@Table(schema = "public")
public class Role extends AbsEntity implements IEntity{
	public String roleName;
	
	public String userId;

	public List<User> children;
	
	private RoleType roleType = RoleType.Manager;
	
	private User user;
	
	public Role() {}
	
	private Role(String roleName) {
		this.roleName = roleName;
	}
	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getDisplayString() {
		System.out.println("I am a Role");
		return "Role";
	}
	
} 



package test.enu;

public enum RoleType{
	Manager,Employee;
}



package test.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "users", schema = "public")
public class User {
	@Id
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid.hex")
	@Column(length = 40)
	@AccessType("property")
	private String id;
	
	private String loginName;
	
	private String password;
	
	private String address;
	
	@ManyToOne
	private Role role;

	public String getId() {
		return id;
	}

	protected void setId(String id) {
		this.id = id;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
}







你可能感兴趣的:(Java Field 详解)