Java リフレクション メカニズムの適用
1. 反射機構
つまり、オブジェクトをインスタンス化することで、所属するクラスの情報が取得されます。
2. クラス構造の取得方法
(1) コンストラクタクラス
クラス内のコンストラクターメソッドを取得する
(2) フィールドクラス
クラス内の属性を取得する
(3) メソッドクラス
クラス内のメソッドを取得する
3. 親クラスの取得方法
c=Class.forName("edu.day1.BookReading");//Class对象
Class<?> c1=c.getSuperclass();
System.out.println("获取父类的名称:"+c.getSuperclass());
4. クラスによって実装されたすべてのインターフェイスを取得する方法
c=Class.forName("edu.day1.BookReading");//Class对象
Class<?> w[]=c.getInterfaces();//获取接口的方法
for (int i=0;i<w.length;i++)
System.out.println("实现的接口名称:"+w[i].getName());
5. クラスのすべての構築メソッドと関連情報を取得する方法
複数の構築メソッドが定義されている場合、複数の構築メソッドの情報が返されます。
c=Class.forName("edu.day1.BookReading");//Class对象
Constructor<?> constructor[] =null;//此处获得对象数组
constructor=c.getConstructors();//获取BookReading类的全部构造方法
for(int i=0;i<constructor.length;i++){
//获取构造方法参数信息
Class<?> p[]=constructor[i].getParameterTypes();
//获取构造方法权限
System.out.print("构造方法权限:"+constructor[i].getModifiers()+" ");
//获取构造方法名称
System.out.print(constructor[i].getName()+"(");
//打印参数信息
for(int j=0;j<p.length;j++){
System.out.print(p[j].getName()+" ");
if(j<p.length-1){
System.out.print(",");
}
}
System.out.print(")");
}
6. クラスのすべてのメソッドを取得する方法
Method method[]=c.getMethods();
for(int i=0;i<method.length;i++){
//获取返回值类型
Class<?> turn=method[i].getReturnType();
//获取参数类型
Class<?> para[]=method[i].getParameterTypes();
//获取修饰符权限
int limit=method[i].getModifiers();
//还原修饰符权限
System.out.println("修饰符权限为:"+ Modifier.toString(limit));
//获取方法抛出异常
Class<?> abnormal[]=method[i].getExceptionTypes();
if(abnormal.length>0){
System.out.println("异常为:");
}
for(int j=0;j<abnormal.length;j++){
System.out.println(abnormal[j].getName());
if(j<abnormal.length-1)
System.out.println(",");
}
}
7. クラスのすべての属性を取得する方法
(1)getFields()可以获取类,及实现的接口或继承的父类的公有属性
如:
Field f[]=c.getFields();
(2)getDeclaredFields()获取类中全部属性包括私有属性
8. リフレクションを通じてクラス内のメソッドを呼び出す方法
c=Class.forName("edu.day1.BookReading");//Class对象
Method method=c.getMethod("类名");
method.invoke(c.newInstance);