简单的代码说明下反射的基本原理.
UserInfo .java
package com.test.mytest;
public class UserInfo {
private int id ;
private String name ;
public UserInfo(){
}
public UserInfo(int id , String name){
this.id = id ;
this.name = name ;
}
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 static void main(String[] args) {
}
}
TestReflect.java
package com.test.mytest;
public class Test {
public static void main(String[] args) {
try {
UserInfo user = (UserInfo)Class.forName("com.test.mytest.UserInfo").newInstance();
user.setId(1);
user.setName("aaa");
} catch (Exception e) {
e.printStackTrace();
}
}
}