工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Java

Java リフレクション API チュートリアルと例


Java のリフレクションとは

Java リフレクションは、実行時にクラスのすべての機能を分析および変更するプロセスです。 Java のリフレクション API は、実行時にフィールド、メソッド、コンストラクターなどを含むクラスとそのメンバーを操作するために使用されます。

Java でのリフレクション API の利点の 1 つは、クラスのプライベート メンバーも操作できることです。

java.lang.reflect パッケージは、リフレクションを実装するための多くのクラスを提供します。 java.lang.Class クラスの java.Methods は、特定のクラスの完全なメタデータを収集するために使用されます。

このチュートリアルで学ぶ内容-

java.lang.reflect パッケージのクラス

以下は、リフレクションを実装するための java.lang.package 内のさまざまな Java クラスのリストです。

java.lang.Class で使用されるメソッド

クラスに関する完全な情報を取得する方法

クラスの変数、メソッド、およびコンストラクターに関する情報を取得するには、クラスのオブジェクトを作成する必要があります。

public class Guru99ClassObjectCreation {
	public static void main (String[] args) throws ClassNotFoundException {
		//1 - By using Class.forname() method 
		Class c1 = Class.forName("Guru99ClassObjectCreation"); 
		//2- By using getClass() method 
		Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation();
		Class c2 = guru99Obj.getClass();
		//3- By using .class 
		Class c3= Guru99ClassObjectCreation.class;
		}
	}
  • 次の例は、クラス「class」のオブジェクトを作成するさまざまな方法を示しています:
  • 例 1 :クラスのメタデータを取得する方法

    次の例は、クラス名、スーパークラス名、実装されたインターフェース、クラスのアクセス修飾子などのメタデータを取得する方法を示しています。

    Guru99Base.class という名前の以下のクラスのメタデータを取得します:

    import java.io.Serializable;
    public abstract class Guru99Base implements Serializable,Cloneable {
    }
    
    <オール>
  • クラス名:Guru99Base
  • アクセス修飾子は public と abstract です
  • Serializable と Cloneable のインターフェースを実装しています
  • クラスを明示的に拡張していないため、スーパークラスは java.lang.Object です
  • 以下のクラスは、Guru99Base.class のメタデータを取得して出力します:

    import java.lang.reflect.Modifier;
    public class Guru99GetclassMetaData {
    
    	public static void main (String [] args) throws ClassNotFoundException { 
    	// Create Class object for Guru99Base.class 
    	Class guru99ClassObj = Guru99Base.class;
    	
    	// Print name of the class 
    	system.out.println("Name of the class is : " +guru99ClassObj.getName());
    	
    	// Print Super class name
    	system.out.println("Name of the super class is : " +guru99ClassObj.getSuperclass().getName());
    	
    	// Get the list of implemented interfaces in the form of Class array using getInterface() method
    	class[] guru99InterfaceList = guru99classObj.getInterfaces();
    	
    	// Print the implemented interfaces using foreach loop 
    	system.out.print("Implemented interfaces are : ");
    	for (Class guru99class1 : quru99 InterfaceList)	{
    		system.out.print guru99class1.getName() + " ");
    	}
    	system.out.println();
    	
    	//Get access modifiers using get Modifiers() method and toString() method of java.lang.reflect.Modifier class
    	int guru99AccessModifier= guru99classObj.getModifiers(); 
    	// Print the access modifiers
    	System.Out.println("Access modifiers of the class are : " +Modifier.tostring(guru99AccessModifier));
    	
    	}
    }
    
    <オール>
  • getName メソッドを使用してクラスの名前を表示
  • getSuperClass().getName() メソッドを使用してスーパー クラスの名前を出力します
  • 実装されたインターフェースの名前を表示
  • クラスで使用されるアクセス修飾子を表示
  • 例 2 :変数のメタデータを取得する方法

    次の例は、変数のメタデータを取得する方法を示しています:

    ここでは、いくつかの変数を持つ Guru99VariableMetaData .class という名前のクラスを作成しています:

    package guru;
    public class Guru99VariableMetaData {				
                   public static int guru99IntVar1=1111;
                   static int guru99IntVar2=2222;							
                   static String guru99StringVar1="guru99.com";							
                    static String guru99StringVar2="Learning Reflection API";    
    }	
    
    上記のクラスの変数に関するメタデータを取得する手順: <オール>
  • 上記のクラス、つまり Guru99VariableMetaData.class のクラス オブジェクトを以下のように作成します:
      Guru99VariableMetaData  guru99ClassVar  = new Guru99VariableMetaData();
      Class  guru99ClassObjVar  = guru99ClassVar.getClass();
  • getFields() を使用してフィールド配列の形式でメタデータを取得します または getDeclaredFields() 以下の方法:
    Field[]  guru99Field1= guru99ClassObjVar .getFields();
    Field[]  guru99Fiel2= guru99ClassObjVar .getDeclaredFields();
  • getFields() メソッドは、指定されたクラスとそのスーパー クラスから public 変数のメタデータを返します。

    getDeclaredFields() メソッドは、指定されたクラスのみからすべての変数のメタデータを返します。

    1. 「public String getName()」メソッドを使用して変数の名前を取得します。
    2. 「public Class getType()」メソッドを使用して変数のデータ型を取得します。
    3. 「public xxx get (Field)」メソッドを使用して変数の値を取得します。

      ここで、xxx は取得したい任意のタイプの値の 1 バイトまたは短い値である可能性があります。

    4. getModifier() および Modifier.toString(int i) メソッドを使用して、変数のアクセス修飾子を取得します。

      ここでは、クラス Guru99VariableMetaData .class に存在する変数のメタデータを取得するクラスを作成しています:

      package guru;
      import java.lang.reflect.Field; 
      
      public class Guru99VariableMetaDataTest {
      	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { 
      	// Create Class object for Guru99VariableMetaData.class 
      	Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); 
      	Class guru99ClassObjVar = guru99ClassVar.getClass();
      	
      	// Get the metadata of all the fields of the class Guru99VariableMetaData 
      	Field[] guru99Field1= guru99ClassObjVar.getDeclaredFields();
      	
      	// Print name, datatypes, access modifiers and values of the varibales of the specified class 
      	for(Field field : guru99Field1) { 
      	System.out.println("Variable name : "+field.getName());
      	System.out.println("Datatypes of the variable :"+field.getType());
      	
      	int guru99AccessModifiers = field.getModifiers();
      	System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(guru99AccessModifiers));
      	System.out.println("Value of the variable : "+field.get(guru99ClassVar));
      	System.out.println();
      	system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ;
      	}
      	}
      }
      
    5. <オール>
    6. Guru99VariableMetaData.class のクラス オブジェクトを作成
    7. Field 配列内の変数のすべてのメタデータを取得
    8. クラス Guru99VariableMetaData.class 内のすべての変数名を出力しました
    9. クラス Guru99VariableMetaData.class 内の変数のすべてのデータ型を表示
    10. クラス Guru99VariableMetaData.class 内の変数のすべてのアクセス修飾子を出力しました
    11. クラス Guru99VariableMetaData.class のすべての変数の値を出力

    例 3 :メソッドのメタデータを取得する方法

    以下の例は、メソッドのメタデータを取得する方法を示しています:

    ここでは、いくつかのメソッドを持つ Guru99MethodMetaData .class という名前のクラスを作成しています

    package guru;		
    import java.sql.SQLException;		
    public class Guru99MethodMetaData {   				
    
    	public void guru99Add(int firstElement, int secondElement , String result) 									
        throws ClassNotFoundException, ClassCastException{			
              System.out.println("Demo method for Reflextion  API");					
        }	
        public String guru99Search(String searchString) 			
        throws ArithmeticException, InterruptedException{			
            System.out.println("Demo method for Reflection API");					
    		return null;					
        }	
    	public void guru99Delete(String deleteString) 					
    	throws SQLException{			
    	    System.out.println("Demo method for Reflection API");					
        }	
    }

    上記のクラスのメソッドに関するメタデータを取得する手順:

    <オール>
  • 上記のクラス、つまり Guru99MethodMetaData.class のクラス オブジェクトを以下のように作成します:
    Guru99MethodMetaData  guru99ClassVar  = new Guru99MethodMetaData  ();
    Class  guru99ClassObjVar  = guru99ClassVar.getClass();
  • 次のように getMethods() および getDeclaredMethods() メソッドを使用して Method 配列のメソッド情報を取得します:
    Method[]  guru99 Method 1= guru99ClassObjVar .get Methods();
    Method []  guru99 Method 2= guru99ClassObjVar .getDeclared Method s();

    getMethods() メソッドは、指定されたクラスとそのスーパー クラスからパブリック メソッドのメタデータを返します。

    getDeclaredMethods() メソッドは、指定されたクラスのみからすべてのメソッドのメタデータを返します。

  • getName() を使用してメソッドの名前を取得します メソッド。
  • getReturnType() を使用してメソッドの戻り値の型を取得します メソッド。
  • getModifiers() を使用してメソッドのアクセス修飾子を取得する そして Modifiers.toString(int i) メソッド。
  • getParameterTypes() を使用してメソッド パラメータ タイプを取得する クラス配列を返すメソッド
  • getExceptionTypes() を使用してスローされた例外を取得します クラス配列を返すメソッド
  • ここでは、クラス Guru99MethodMetaData.class に存在するメソッドのメタデータを取得するクラスを作成しています:

    package guru;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    public class Guru99MethodMetaDataTest { 
    
    	public static void main (String[] args) {
    		// Create Class object for Guru99Method MetaData.class 
    		class guru99ClassObj = Guru99MethodMetaData.class;
    
    		// Get the metadata or information of all the methods of the class using getDeclaredMethods() 
    		Method[] guru99Methods=guru99classObj.getDeclaredMethods();
    
    		for(Method method : guru99Methods) { 
    		// Print the method names
    		System.out.println("Name of the method : "+method.getName());
    		
    		// Print return type of the methods 
    		System.out.println("Return type of the method : "+method.getReturnType());
    		
    		//Get the access modifier list and print
    		int guru99ModifierList = method.getModifiers(); 
    		System.Out.printlin ("Method access modifiers : "+Modifier.toString(guru99ModifierList));
    		
    		// Get and print parameters of the methods 
    		Class[] guru99ParamList= method.getParameterTypes(); 
    		system.out.print ("Method parameter types : "); 
    		for (Class class1 : guru99ParamList){ 
    			System.out.println(class1.getName()+" ");
    		}
            System.out.println();
    		
    		// Get and print exception thrown by the method 
    		Class[] guru99ExceptionList = method. getExceptionTypes(); 
    		system.out.print("Excpetion thrown by method :"); 
    		for (Class class1 : guru99ExceptionList) {
    			System.out.println (class1.getName() +" "):
    		} 
    		System.Out.println(); 
    		system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ");
    		
    		}
     
    	}
    }
    
    <オール>
  • Guru99MethodMetaData.class のクラス オブジェクトを作成
  • メソッド配列内のすべてのメソッドのすべてのメタデータを取得
  • クラス Guru99MethodMetaData.class に存在するすべてのメソッド名を出力しました
  • クラス Guru99MethodMetaData.class のメソッドの戻り値の型を出力
  • クラス Guru99MethodMetaData.class 内のメソッドのすべてのアクセス修飾子を出力しました
  • Guru99MethodMetaData.class 内のメソッドの出力パラメータ タイプ
  • 印刷された例外は、Guru99MethodMetaData.class のメソッドによってスローされます

  • 例 4 :コンストラクターのメタデータを取得する方法

    次の例は、コンストラクターのメタデータを取得する方法を示しています:

    ここでは、さまざまなコンストラクターを持つ Guru99Constructor.class という名前のクラスを作成しています:

    package guru;		
    
    import java.rmi.RemoteException;		
    import java.sql.SQLException;		
    
    public class Guru99Constructor {				
    
    	public Guru99Constructor(int no) throws ClassCastException ,ArithmeticException{  }							
    	public Guru99Constructor(int no, String name) throws RemoteException ,SQLException{  }							
    	public Guru99Constructor(int no, String name, String address) throws InterruptedException{  }							
    }

    ここでは、クラス Guru99Constructor.class に存在するコンストラクターのメタデータを取得するクラスを作成しています:

    package guru;
    import java.lang.reflect.Constructor; 
    public class Guru99ConstructorMetaDataTest {
    	
    	public static void main (String[] args) {
    		// Create Class object for Guru99Constructor.class 
    		Class guru99Class=Guru99Constructor.class;
    
    		// Get all the constructor information in the Constructor array
    		Constructor[] guru99ConstructorList = guru99Class.getConstructors();
    		
    		for (Constructor constructor : guru99ConstructorList) {
    			// Print all name of each constructor
    			System.out.println("Constrcutor name : "+constructor.getName());
    			
    			//Get and print access modifiers of each constructor 
    			int guru99Modifiers= constructor.getModifiers(); 
    			System.Out.printlin ("Constrctor modifier : "+Modifier.toString(guru99Modifiers));
    			
    			// Get and print parameter types 
    			Class[] guru99ParamList=constructor.getParameterTypes();
    			System.out.print ("Constrctor parameter types :"); 
    			for (Class class1 : guru99ParamList) { 
    				System.out.println(class1.getName() +" ");
    			}
    			System. out.println();
    
    			// Get and print exception thrown by constructors
    			Class[] guru99ExceptionList=constructor.getFxceptionTypes();
    			System.out.println("Exception thrown by constructors :"); 
    			for (Class class1 : guru99ExceptionList) { 
    				System.out.println(class1.getName() +" ");
    			} 
    			System.out.println();
    			System.out.println("*******************************************");
    		}
    	}
    }
     
    
    
    
    
    <オール>
  • Guru99Constructor.class のクラス オブジェクトを作成
  • Constructor 配列内のすべてのコンストラクターのすべてのメタデータを取得
  • クラス Guru99Constructor.class に存在するすべてのコンストラクターの名前を出力しました
  • クラス Guru99Constructor.class 内のコンストラクターのすべてのアクセス修飾子を出力しました
  • Guru99Constructor.class 内のコンストラクターの出力されたパラメーターの型
  • 印刷された例外は、Guru99Constructor.class のコンストラクターによってスローされます
  • まとめ:


    Java

    1. Java匿名クラス
    2. Java リフレクション
    3. Java ObjectInputStream クラス
    4. Java ObjectOutputStream クラス
    5. C++ クラスとオブジェクトと例
    6. 例を含む C# クラスとオブジェクトのチュートリアル
    7. 例を含む C# 抽象クラスのチュートリアル:抽象化とは?
    8. Java String charAt() メソッドと例
    9. 例を使用したJava文字列のendsWith()メソッド
    10. Java BufferedReader:例を使用して Java でファイルを読み取る方法
    11. プログラム例を使用した Java の挿入ソート アルゴリズム