Java Field 詳解

一.主要方法

getType(): 獲取屬性聲明時類型對象(返回class對象)
java

getGenericType() : 返回屬性的泛型類型
ui

getName() : 獲取屬性聲明時名字 this

getAnnotations() : 得到這個屬性上全部的註釋
spa

getModifiers() : 獲取屬性的修飾 hibernate

isEnumConstant() : 判斷這個屬性是不是枚舉類 code

isSynthetic() : 判斷這個屬性是不是 複合類
orm

get(Object obj) : 取得obj對象這個Field上的值
對象

set(Object obj, Object value) : 向obj對象的這個Field設置新值value
接口

Field類中最經常使用的是get(Object obj)和set(Object obj, Object value)這兩個方法,因此這兩個方法是最重要的。 get

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;
	}
}
相關文章
相關標籤/搜索