Java リフレクション
Java リフレクション
このチュートリアルでは、クラスやメソッドなどを検査および変更できる Java プログラミングの機能であるリフレクションについて学習します。
Java では、リフレクションを使用して、実行時にクラス、インターフェイス、コンストラクター、メソッド、およびフィールドを検査および操作できます。
Java には Class
という名前のクラスがあります 実行時にオブジェクトとクラスに関するすべての情報を保持します。 Class のオブジェクト リフレクションの実行に使用できます。
Java クラスの反映
Java クラスを反映するには、まず Class のオブジェクトを作成する必要があります .
また、オブジェクトを使用してさまざまなメソッドを呼び出し、クラスに存在するメソッド、フィールド、およびコンストラクターに関する情報を取得できます。
クラスのオブジェクトを作成する方法は 3 つあります:
<強い>1. forName() メソッドの使用
class Dog {...}
// create object of Class
// to reflect the Dog class
Class a = Class.forName("Dog");
ここでは、forName()
メソッドは、その引数として反映されるクラスの名前を取ります。
<強い>2. getClass() メソッドの使用
// create an object of Dog class
Dog d1 = new Dog();
// create an object of Class
// to reflect Dog
Class b = d1.getClass();
ここでは、Dog のオブジェクトを使用しています Class のオブジェクトを作成するクラス .
<強い>3. .class 拡張子の使用
// create an object of Class
// to reflect the Dog class
Class c = Dog.class;
Class
のオブジェクトを作成する方法がわかったので、 .このオブジェクトを使用して、実行時に対応するクラスに関する情報を取得できます。
例:Java クラスのリフレクション
import java.lang.Class;
import java.lang.reflect.*;
class Animal {
}
// put this class in different Dog.java file
public class Dog extends Animal {
public void display() {
System.out.println("I am a dog.");
}
}
// put this in Main.java file
class Main {
public static void main(String[] args) {
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// get name of the class
String name = obj.getName();
System.out.println("Name: " + name);
// get the access modifier of the class
int modifier = obj.getModifiers();
// convert the access modifier to string
String mod = Modifier.toString(modifier);
System.out.println("Modifier: " + mod);
// get the superclass of Dog
Class superClass = obj.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
}
catch (Exception e) {
e.printStackTrace();
}
}
}
出力
Name: Dog Modifier: public Superclass: Animal
上記の例では、スーパークラス Animal を作成しました。 サブクラス:犬 .ここでは、クラス Dog を検査しようとしています。 .
声明に注目してください、
Class obj = d1.getClass();
ここでは、オブジェクト obj を作成しています クラスの getClass()
を使用して 方法。オブジェクトを使用して、Class のさまざまなメソッドを呼び出しています .
- obj.getName() - クラスの名前を返します
- obj.getModifiers() - クラスのアクセス修飾子を返します
- obj.getSuperclass() - クラスのスーパークラスを返します
Class
について詳しく知るには 、Java クラス (公式の Java ドキュメント) にアクセスしてください。
注意 :Modifier
を使用しています 整数アクセス修飾子を文字列に変換するクラス
フィールド、メソッド、コンストラクターの反映
パッケージ java.lang.reflect
クラスメンバーの操作に使用できるクラスを提供します。たとえば、
- メソッド クラス - クラスのメソッドに関する情報を提供します
- フィールド クラス - クラスのフィールドに関する情報を提供します
- コンストラクタ クラス - クラスのコンストラクターに関する情報を提供します
1. Java メソッドの反映
Method
クラスは、クラスに存在するメソッドに関する情報を取得するために使用できるさまざまなメソッドを提供します。たとえば、
import java.lang.Class;
import java.lang.reflect.*;
class Dog {
// methods of the class
public void display() {
System.out.println("I am a dog.");
}
private void makeSound() {
System.out.println("Bark Bark");
}
}
class Main {
public static void main(String[] args) {
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// using object of Class to
// get all the declared methods of Dog
Method[] methods = obj.getDeclaredMethods();
// create an object of the Method class
for (Method m : methods) {
// get names of methods
System.out.println("Method Name: " + m.getName());
// get the access modifier of methods
int modifier = m.getModifiers();
System.out.println("Modifier: " + Modifier.toString(modifier));
// get the return types of method
System.out.println("Return Types: " + m.getReturnType());
System.out.println(" ");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
出力
Method Name: display Modifier: public Return Types: void Method Name: makeSound Modifier: private Return Types: void
上記の例では、Dog に存在するメソッドに関する情報を取得しようとしています。 クラス。前述のように、最初にオブジェクト obj を作成しました Class
の getClass()
を使用して メソッド。
表現に注目してください、
Method[] methods = obj.getDeclaredMethod();
ここでは、getDeclaredMethod()
クラス内に存在するすべてのメソッドを返します。
また、オブジェクト m を作成しました Method
の クラス。ここで、
- m.getName() - メソッドの名前を返します
- m.getModifiers() - メソッドのアクセス修飾子を整数形式で返します
- m.getReturnType() - メソッドの戻り型を返します
Method
クラスは、実行時にメソッドを検査するために使用できる他のさまざまなメソッドも提供します。詳細については、Java Method クラス (公式の Java ドキュメント) を参照してください。
2. Java フィールドの反映
メソッドと同様に、Field
のメソッドを使用して、クラスのさまざまなフィールドを検査および変更することもできます。 クラス。たとえば、
import java.lang.Class;
import java.lang.reflect.*;
class Dog {
public String type;
}
class Main {
public static void main(String[] args) {
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// access and set the type field
Field field1 = obj.getField("type");
field1.set(d1, "labrador");
// get the value of the field type
String typeValue = (String) field1.get(d1);
System.out.println("Value: " + typeValue);
// get the access modifier of the field type
int mod = field1.getModifiers();
// convert the modifier to String form
String modifier1 = Modifier.toString(mod);
System.out.println("Modifier: " + modifier1);
System.out.println(" ");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
出力
Value: labrador Modifier: public
上記の例では、Dog という名前のクラスを作成しました。 . type という名前の public フィールドが含まれています .声明に注目してください、
Field field1 = obj.getField("type");
ここでは、Dog のパブリック フィールドにアクセスしています。 クラスを作成し、それをオブジェクト field1 に割り当てます フィールドの クラス。
次に、Field
のさまざまな方法を使用しました。 クラス:
- field1.set() - フィールドの値を設定します
- field1.get() - フィールドの値を返します
- field1.getModifiers() - フィールドの値を整数形式で返します
同様に、プライベート フィールドにアクセスして変更することもできます。ただし、private フィールドの反映は public フィールドとは少し異なります。たとえば、
import java.lang.Class;
import java.lang.reflect.*;
class Dog {
private String color;
}
class Main {
public static void main(String[] args) {
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// access the private field color
Field field1 = obj.getDeclaredField("color");
// allow modification of the private field
field1.setAccessible(true);
// set the value of color
field1.set(d1, "brown");
// get the value of field color
String colorValue = (String) field1.get(d1);
System.out.println("Value: " + colorValue);
// get the access modifier of color
int mod2 = field1.getModifiers();
// convert the access modifier to string
String modifier2 = Modifier.toString(mod2);
System.out.println("Modifier: " + modifier2);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
出力
Value: brown Modifier: private
上記の例では、Dog という名前のクラスを作成しました。 .このクラスには、color という名前のプライベート フィールドが含まれています .ステートメントに注目してください。
Field field1 = obj.getDeclaredField("color");
field1.setAccessible(true);
ここでは、color にアクセスしています。 オブジェクト field1 に割り当てます Field
のうち クラス。次に、field1 を使用しました color のアクセシビリティを変更するには 変更を加えることができます。
次に、field1 を使用して、プライベート フィールド color に対してさまざまな操作を実行しました。
Field のさまざまなメソッドについて詳しく知るには 、Java フィールド クラス (公式の Java ドキュメント) にアクセスしてください。
3. Java コンストラクターのリフレクション
Constructor
によって提供されるさまざまなメソッドを使用して、クラスのさまざまなコンストラクターを検査することもできます。 クラス。たとえば、
import java.lang.Class;
import java.lang.reflect.*;
class Dog {
// public constructor without parameter
public Dog() {
}
// private constructor with a single parameter
private Dog(int age) {
}
}
class Main {
public static void main(String[] args) {
try {
// create an object of Dog
Dog d1 = new Dog();
// create an object of Class
// using getClass()
Class obj = d1.getClass();
// get all constructors of Dog
Constructor[] constructors = obj.getDeclaredConstructors();
for (Constructor c : constructors) {
// get the name of constructors
System.out.println("Constructor Name: " + c.getName());
// get the access modifier of constructors
// convert it into string form
int modifier = c.getModifiers();
String mod = Modifier.toString(modifier);
System.out.println("Modifier: " + mod);
// get the number of parameters in constructors
System.out.println("Parameters: " + c.getParameterCount());
System.out.println("");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
出力
Constructor Name: Dog Modifier: public Parameters: 0 Constructor Name: Dog Modifier: private Parameters: 1
上記の例では、Dog という名前のクラスを作成しました。 .このクラスには 2 つのコンストラクターが含まれています。
リフレクションを使用して、クラスのコンストラクターに関する情報を見つけています。声明に注目してください、
Constructor[] constructors = obj.getDeclaredConstructor();
ここでは、Dog に存在するすべてのコンストラクターにアクセスしています。 それらを配列 constructors に割り当てます Constructor
の タイプしてください。
次に、オブジェクト c を使用しました コンストラクターに関するさまざまな情報を取得します。
- c.getName() - コンストラクタの名前を返します
- c.getModifiers() - コンストラクターのアクセス修飾子を整数形式で返します
- c.getParameterCount() - 各コンストラクターに存在するパラメーターの数を返します
Constructor
のその他のメソッドについて学ぶには クラス、コンストラクター クラスにアクセス
Java