反射:通过反射调用属性

版权声明:版权所有@万星明 https://blog.csdn.net/qq_19533277/article/details/83714014
import java.lang.reflect.Field;

/** 
* @author  万星明
* @version 创建时间:2018年10月26日 上午10:43:23 
*/
public class 反射属性调用 {
	public static void main(String[] args) throws Exception {
		
		//创建反射对象
		Class clazz = Class.forName("反射与URL.Student");
		//通过反射对象创建实例对象
		Object ob1 = clazz.newInstance();
		
		//获取类私有的属性
		Field ageField = clazz.getDeclaredField("age");
		//设置属性的访问权限
		ageField.setAccessible(true);
		//给私有的或者公有的属性赋值
		ageField.set(ob1, 11);
		System.out.println(ageField.get(ob1));
	
	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_19533277/article/details/83714014