[置頂]JAVAの内省
プログラマーたちがJavaオブジェクトのプロパティをよりよく操作できるように、SUN社はAPIを開発し、業界内では「内省」と呼ばれている.内省の出現はクラスオブジェクト属性の操作に有利であり,コードの数を減らす.
内省がJavaBeanにアクセスするには、次の2つの方法があります.
一、IntrospectorクラスでBeanオブジェクトを獲得する BeanInfo、そして BeanInfo プロパティを取得するディスクリプタ( PropertyDescriptor ),このプロパティ記述器で、あるプロパティに対応する getter/setter メソッドは、反射メカニズムによって呼び出されます.
二、BeanオブジェクトをPropertyDescriptorで操作する
次はStudent クラスオブジェクトが操作されます.Studioクラスのソースコードは次のとおりです.
まず、第一の方式で、ソースコードは以下の通りです.
実行結果:
class
class java.lang.Class
name
class java.lang.String
xxx
class java.lang.String
Lou_Wazor
次に、Beanオブジェクトを2つ目の方法で操作します.ソースコードは次のとおりです.
実行結果:
Lou_Wazor
Lou_Wazor
以上は自省のいくつかの知識点で、みんなが互いに交流して、意見と問題を提出して、討論学習を行うことを望んでいます.
内省がJavaBeanにアクセスするには、次の2つの方法があります.
一、IntrospectorクラスでBeanオブジェクトを獲得する BeanInfo、そして BeanInfo プロパティを取得するディスクリプタ( PropertyDescriptor ),このプロパティ記述器で、あるプロパティに対応する getter/setter メソッドは、反射メカニズムによって呼び出されます.
二、BeanオブジェクトをPropertyDescriptorで操作する
次はStudent クラスオブジェクトが操作されます.Studioクラスのソースコードは次のとおりです.
public class Student {
private String name;//
public String getXxx(){//
return "xx";
}
public String setXxx(){//
return "xx";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
まず、第一の方式で、ソースコードは以下の通りです.
@Test
public void test() throws Exception{
Student student = new Student();
//1. Introspector bean beaninfo
BeanInfo bif = Introspector.getBeanInfo(Student.class);
//2. beaninfo (propertyDescriptor)
PropertyDescriptor pds[] = bif.getPropertyDescriptors();
//3. get/set
for(PropertyDescriptor pd:pds){
//4.
System.out.println(pd.getName());
//5.
System.out.println(pd.getPropertyType());
if(pd.getName().equals("name")){
//6. PropertyDescriptor
Method md = pd.getWriteMethod();
//7.
md.invoke(student, "Lou_Wazor");
}
}
//8.
System.out.println(student.getName());
}
実行結果:
class
class java.lang.Class
name
class java.lang.String
xxx
class java.lang.String
Lou_Wazor
次に、Beanオブジェクトを2つ目の方法で操作します.ソースコードは次のとおりです.
@Test
public void test01()throws Exception{
Student st = new Student();
//1. PropertyDescriptor
PropertyDescriptor pd = new PropertyDescriptor("name", Student.class);
//2.
Method method = pd.getWriteMethod();
//3.
method.invoke(st, "Lou_Wazor");
//4.
System.out.println(st.getName());
//5.
method = pd.getReadMethod();
//6.
String name = (String) method.invoke(st, null);
//7.
System.out.println(name);
}
実行結果:
Lou_Wazor
Lou_Wazor
以上は自省のいくつかの知識点で、みんなが互いに交流して、意見と問題を提出して、討論学習を行うことを望んでいます.