JAvaの内省
2131 ワード
JAvaの反射技術は,開発者にメンバー変数,メンバーメソッド,構造関数などの操作方法を提供する.多くの場合、オブジェクトの属性でデータをカプセル化し、反射技術でこのような操作を完了するのは煩雑で、内省的な出現があり、その役割は、オブジェクトの属性を操作するために使用され、コード量を大幅に軽減することである.
まずJavaBeanとは何かを理解します.
JAvaBeanは実はjavaクラスですが、このクラスには一定の仕様があり、そのクラスは具体的で共通であり、パラメータのない構造関数を持っていなければなりません.もちろん、javaBeanに関する仕様はまだたくさんありますが、例を見ると分かりやすいはずです.
JAvaの内省はオブジェクト属性を操作するために使われていますが、上記のPersonクラスにはどのような属性がありますか?
name属性age属性class属性(この属性はObjectクラスから継承され、ObjectにgetClass()メソッドがあります)
内省を通じてPersonの属性を簡単に操作する方法を紹介します.
まずJavaBeanとは何かを理解します.
JAvaBeanは実はjavaクラスですが、このクラスには一定の仕様があり、そのクラスは具体的で共通であり、パラメータのない構造関数を持っていなければなりません.もちろん、javaBeanに関する仕様はまだたくさんありますが、例を見ると分かりやすいはずです.
public class Person {
private String name;
private int age;
public Person(){}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
}
JAvaの内省はオブジェクト属性を操作するために使われていますが、上記のPersonクラスにはどのような属性がありますか?
name属性age属性class属性(この属性はObjectクラスから継承され、ObjectにgetClass()メソッドがあります)
内省を通じてPersonの属性を簡単に操作する方法を紹介します.
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntrospectorTest {
public static void main(String[] args) throws Exception {
// test1(); //
test2(); //
}
//
private static void test2() throws Exception {
// Person name
PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);
// setName()
Method write = pd.getWriteMethod();
Person p = new Person();
//
write.invoke(p, "java");
// getName()
Method read = pd.getReadMethod();
String name = (String) read.invoke(p, null);
System.out.println(name);
}
//
private static void test1() throws Exception {
// Bean
BeanInfo info = Introspector.getBeanInfo(Person.class);
// info
// BeanInfo info = Introspector.getBeanInfo(Person.class,Object.class);
//
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (PropertyDescriptor p : pds) {
//
System.out.println(p.getName());
//
System.out.println(p.getPropertyType());
}
}
}