反射机制实例化类,并获取类中的属性、方法、和构造器
1.先写一个JavaBean类:
package com.buaa.reflectTest;
public class User {
private int id;
private int age;
private String uname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public User(int id, int age, String uname) {
super();
this.id = id;
this.age = age;
this.uname = uname;
}
public User() {
}
}
2.利用反射机制获取do something....
package com.buaa.reflectTest;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Demo01 {
public static void main(String[] args) {
String path = "com.buaa.reflectTest.User";
try {
Class<User> clazz = (Class<User>)Class.forName(path);
//get constructor
Constructor con = clazz.getDeclaredConstructor(int.class,int.class,String.class);
User u = (User)con.newInstance(1,19,"maomi");
System.out.println(u.getUname());
//get Method
Method m = clazz.getDeclaredMethod("setAge", int.class);
m.setAccessible(true);
m.invoke(u, 20);
System.out.println(u.getAge());
//get field
Field f = clazz.getDeclaredField("id");
f.setAccessible(true); //设置访问权限
f.set(u, 3);
System.out.println(u.getId());
} catch (Exception e) {
e.printStackTrace(http://www.amjmh.com);
}
}
}
---------------------