JAva反射----指定したクラスの属性と方法を取得する
2588 ワード
Person.JAvaコードは次のとおりです.
Test.JAvaコードは次のとおりです.
実行結果は次のとおりです.
package com.reflect.bean;
public class Person {
private String name;
private int age;
public Person(){
}
public Person(int age){
this.age = age;
}
public Person(String name){
this.name = name;
}
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 "["+this.name+" "+this.age+"]";
}
}
Test.JAvaコードは次のとおりです.
package com.reflect.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.reflect.bean.Person;
public class Test {
public static void main(String[] args) {
Class<?> demo = null;
try{
demo = Class.forName("com.reflect.bean.Person");
}catch (Exception e) {
e.printStackTrace();
}
Person person1 = null;
Person person2 = null;
Person person3 = null;
Person person4 = null;
Constructor<?> cons[] = demo.getConstructors();
try{
person1 = (Person)cons[3].newInstance();
person2 = (Person)cons[1].newInstance("zhangsan");
person3 = (Person)cons[0].newInstance(20);
person4 = (Person)cons[2].newInstance("lisi",20);
}catch (Exception e) {
e.printStackTrace();
}
Field[] field = demo.getDeclaredFields();
Method[] method = demo.getDeclaredMethods();
System.out.println("method : "+method[0]);
System.out.println("field : "+field[0]);
System.out.println(person1);
System.out.println(person2);
System.out.println(person3);
System.out.println(person4);
}
}
実行結果は次のとおりです.
method : public java.lang.String com.reflect.bean.Person.toString()
field : private java.lang.String com.reflect.bean.Person.name
[null 0]
[zhangsan 0]
[null 20]
[lisi 20]