java反射给实体类赋值

给实体类赋值有两种方法,一个是通过Field.set()方法,另一个是Method.invoke();

至于两种方法的区别,还想请教:

我知道的:set直接给属性赋值,invoke通过调用属性的set方法赋值


好了上代码:

实体类:

package testReflect;

public class UserEntity {
	private int id;
	private String name;
	private boolean male;
	private boolean isMale;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean getMale() {
		return male;
	}
	public void setMale(boolean male) {
		this.male = male;
//		this.isMale = male;
	}
	public boolean isMale() {
		return isMale;
	}
}

实现类

package testReflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestSetAndInvoke {
	public static UserEntity testSet() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
		UserEntity ue = new UserEntity();
		//UserEntity.class和ue.getClass()有什么不同?
		//.class是属性 ue.getClass()需要实例化 是方法
		Field f1= UserEntity.class.getDeclaredField("id");
		Field f2= ue.getClass().getDeclaredField("name");
		//该属性没有set方法
		Field f3= ue.getClass().getDeclaredField("isMale");
		//该属性有set方法
		Field f4= ue.getClass().getDeclaredField("male");
		//私有属性设置可访问
		f1.setAccessible(true);
		f2.setAccessible(true);
		f3.setAccessible(true);
		f4.setAccessible(true);
		//给ue的f1(id属性)设置值为1
		f1.set(ue, 1);
		//给ue的f2(name属性)设置值为kon
		f2.set(ue, "kon");
		//给ue的f3(isMale属性)设置值为true
		f3.set(ue, true);
		//给ue的f4(male属性)设置值为true
		f4.set(ue, true);
		
		return ue;
	}
	
	public static UserEntity testInvoke() throws InvocationTargetException, IllegalArgumentException, IllegalAccessException{
		UserEntity ue = new UserEntity();
		Method[] allMethods= UserEntity.class.getDeclaredMethods();
		//获得的allMethods是无顺序的;
		for (Method method : allMethods) {
			if(method.getName().startsWith("get")){
				System.out.println(method.getName());
			}else{
				System.out.println(method.getName());
				if("setId".equals(method.getName())){
					method.invoke(ue,1);
				}else if("setName".equals(method.getName())){
					method.invoke(ue,"kon");
				}else if("setMale".equals(method.getName())){
					method.invoke(ue,true);
				}else{
					System.out.println("不用设置");
				}
			}
		}
		
		return ue;
	}
	
	
	public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InvocationTargetException {
//		UserEntity ue = testSet();
		UserEntity ue = testInvoke();
		System.out.println(ue.getId()+":"+ue.getName()+" isMale--> "+ue.isMale()+" male: "+ue.getMale());
	}
}

输出结果

1:kon isMale--> true male: true
isMale
不用设置
setId
setMale
getMale
getName
getId
setName
1:kon isMale--> false male: true

你可能感兴趣的:(java)