クラス名 ( としてString
) があり、すべてのメンバーとその型を取得したいと考えています。リフレクションを使用する必要があることはわかっていますが、どうすればよいでしょうか。
たとえば、私が持っている場合
class MyClass {
Integer a;
String b;
}
a
と の型と名前を取得するにはどうすればよいb
ですか?
クラス名 ( としてString
) があり、すべてのメンバーとその型を取得したいと考えています。リフレクションを使用する必要があることはわかっていますが、どうすればよいでしょうか。
たとえば、私が持っている場合
class MyClass {
Integer a;
String b;
}
a
と の型と名前を取得するにはどうすればよいb
ですか?
クラスが jvm によってすでにロードされている場合は、Class.forName(String className); という Class の静的メソッドを使用できます。そして、反射オブジェクトへのハンドルを返します。
あなたがするだろう:
//get class reflections object method 1
Class aClassHandle = Class.forName("MyClass");
//get class reflections object method 2(preferred)
Class aClassHandle = MyClass.class;
//get a class reflections object method 3: from an instance of the class
MyClass aClassInstance = new MyClass(...);
Class aClassHandle = aClassInstance.getClass();
//get public class variables from classHandle
Field[] fields = aClassHandle.getFields();
//get all variables of a class whether they are public or not. (may throw security exception)
Field[] fields = aClassHandle.getDeclaredFields();
//get public class methods from classHandle
Method[] methods = aClassHandle.getMethods();
//get all methods of a class whether they are public or not. (may throw security exception)
Method[] methods = aClassHandle.getDeclaredMethods();
//get public class constructors from classHandle
Constructor[] constructors = aClassHandle.getConstructors();
//get all constructors of a class whether they are public or not. (may throw security exception)
Constructor[] constructors = aClassHandle.getDeclaredConstructors();
MyClass から b という名前の変数を取得するには、そうすることができます。
Class classHandle = Class.forName("MyClass");
Field b = classHandle.getDeclaredField("b");
b が整数型の場合、その値を取得するには i が行います。
int bValue = (Integer)b.get(classInstance);//if its an instance variable`
また
int bValue = (Integer)b.get(null);//if its a static variable