1 源码
public class Person {
public String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public void show(String name,int age){
System.out.println("(一般方法:name="+name+",age="+age+")");
}
public static void staticShow(){
System.out.println("(静态方法)");
}
}
2 获取构造器
public class Relect_getContruct {
public static void main(String[] args) throws Exception {
String className = "com.java.domain.Person";
Class class01 = Class.forName(className);
Constructor con = class01.getConstructor(String.class,int.class);
Object obj = con.newInstance("coco",18);
System.out.println(obj);
}
}
3 获取字段
public static void main(String[] args) throws Exception {
getField();
}
public static void getField() throws Exception {
String className = "com.java.domain.Person";
Class class1 = Class.forName(className);
String name = "name";
String age = "age";
Field field_name = class1.getField(name);
Field field_age = class1.getDeclaredField(age);
Object obj = class1.newInstance();
field_name.set(obj, "coco");
field_name.set(obj, "coco");
field_age.setAccessible(true);
field_age.set(obj, 18);
System.out.println(field_name.get(obj));
System.out.println(field_age.get(obj));
System.out.println(obj);
}
}
4 获取方法
public static void main(String[] args) throws Exception {
getMethodDemo();
getStaticMethodDemo();
}
public static void getMethodDemo() throws Exception {
String className = "com.java.domain.Person";
Class class1 = Class.forName(className);
String methodName = "show";
Method methodObj = class1.getMethod(methodName, String.class, int.class);
Object obj = class1.newInstance();
methodObj.invoke(obj, "amo", 28);
}
public static void getStaticMethodDemo() throws Exception {
String className = "com.java.domain.Person";
Class class1 = Class.forName(className);
String methodName = "staticShow";
Method methodObj = class1.getMethod(methodName, null);
Object obj = class1.newInstance();
methodObj.invoke(null,null);
}
}