산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

예제가 있는 Java Reflection API 자습서


자바에서 리플렉션이란 무엇입니까?

Java Reflection은 런타임에 클래스의 모든 기능을 분석하고 수정하는 프로세스입니다. Java의 Reflection API는 런타임에 필드, 메소드, 생성자 등을 포함하는 클래스 및 해당 멤버를 조작하는 데 사용됩니다.

Java에서 리플렉션 API의 한 가지 장점은 클래스의 private 멤버도 조작할 수 있다는 것입니다.

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 {
    }
    
    1. 클래스 이름:Guru99Base
    2. 액세스 수정자는 public 및 abstract입니다.
    3. 직렬화 가능 및 복제 가능 인터페이스를 구현했습니다.
    4. 명시적으로 클래스를 확장하지 않았기 때문에 상위 클래스는 java.lang.Object
    5. 입니다.

    아래 클래스는 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));
    	
    	}
    }
    
    1. getName 메소드를 사용하여 클래스 이름 출력
    2. getSuperClass().getName() 메소드를 사용하여 수퍼 클래스의 이름을 인쇄합니다.
    3. 구현된 인터페이스의 이름 인쇄
    4. 클래스에서 사용하는 액세스 수정자를 인쇄합니다.

    예시 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";    
    }	
    
    위 클래스의 변수에 대한 메타데이터를 가져오는 단계:
    1. Guru99VariableMetaData.class와 같은 위 클래스의 클래스 객체를 아래와 같이 생성합니다.
        Guru99VariableMetaData  guru99ClassVar  = new Guru99VariableMetaData();
        Class  guru99ClassObjVar  = guru99ClassVar.getClass();
    2. getFields()를 사용하여 필드 배열 형식의 메타데이터 가져오기 또는 getDeclaredFields() 아래와 같은 방법:
      Field[]  guru99Field1= guru99ClassObjVar .getFields();
      Field[]  guru99Fiel2= guru99ClassObjVar .getDeclaredFields();

    getFields() 메서드는 지정된 클래스와 해당 슈퍼 클래스에서 공용 변수의 메타데이터를 반환합니다.

    getDeclaredFields() 메서드는 지정된 클래스의 모든 변수에 대한 메타데이터만 반환합니다.

    <올 시작="3">
  • "public String getName()" 메소드를 사용하여 변수의 이름을 가져옵니다.
  • "public Class getType()" 메소드를 사용하여 변수의 데이터 유형을 가져옵니다.
  • "public xxx get(Field)" 메소드를 사용하여 변수의 값을 가져옵니다.

    여기에서 xxx는 우리가 가져오려는 값의 바이트 또는 짧은 값일 수 있습니다.

  • getModifier() 및 Modifier.toString(int i) 메서드를 사용하여 변수의 액세스 수정자를 가져옵니다.

    여기에서는 Guru99VariableMetaData 클래스에 있는 변수의 메타데이터를 가져오는 클래스를 작성합니다.

    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("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ;
    	}
    	}
    }
    
    1. Guru99VariableMetaData.class용 클래스 객체 생성
    2. 필드 배열에 있는 변수의 모든 메타데이터 가져오기
    3. Guru99VariableMetaData.class 클래스의 모든 변수 이름을 출력했습니다.
    4. Guru99VariableMetaData.class 클래스에 있는 변수의 모든 데이터 유형을 출력합니다.
    5. Guru99VariableMetaData.class 클래스에 있는 변수의 모든 액세스 수정자를 인쇄했습니다.
    6. 모든 변수의 값 출력 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");					
        }	
    }

    위 클래스의 메소드에 대한 메타데이터를 가져오는 단계:

    1. Guru99MethodMetaData.class와 같은 위 클래스의 클래스 객체를 아래와 같이 생성합니다.
      Guru99MethodMetaData  guru99ClassVar  = new Guru99MethodMetaData  ();
      Class  guru99ClassObjVar  = guru99ClassVar.getClass();
    2. 아래와 같이 getMethods() 및 getDeclaredMethods() 메서드를 사용하여 메서드 배열의 메서드 정보 가져오기:
      Method[]  guru99 Method 1= guru99ClassObjVar .get Methods();
      Method []  guru99 Method 2= guru99ClassObjVar .getDeclared Method s();

      getMethods() 메서드는 지정된 클래스와 해당 슈퍼 클래스에서 공개 메서드의 메타데이터를 반환합니다.

      getDeclaredMethods() 메서드는 지정된 클래스의 모든 메서드에 대한 메타데이터만 반환합니다.

    3. getName() 을 사용하여 메서드 이름 가져오기 방법.
    4. getReturnType() 을 사용하여 메서드의 반환 유형 가져오기 방법.
    5. getModifiers()를 사용하여 메소드의 액세스 수정자 가져오기 및 Modifiers.toString(int i) 방법.
    6. getParameterTypes() 를 사용하여 메소드 매개변수 유형 가져오기 클래스 배열을 반환하는 메서드입니다.
    7. 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("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ");
    		
    		}
     
    	}
    }
    
    1. Guru99MethodMetaData.class용 클래스 객체 생성
    2. 메소드 배열에 있는 모든 메서드의 모든 메타데이터 가져오기
    3. Guru99MethodMetaData.class 클래스에 있는 모든 메소드 이름을 인쇄했습니다.
    4. Guru99MethodMetaData.class 클래스에 있는 메서드의 인쇄된 반환 유형
    5. Guru99MethodMetaData.class 클래스에 있는 메소드의 모든 액세스 수정자를 인쇄했습니다.
    6. Guru99MethodMetaData.class에 있는 메소드의 인쇄된 매개변수 유형
    7. 인쇄된 예외는 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("*******************************************");
    		}
    	}
    }
     
    
    
    
    
    1. Guru99Constructor.class용 클래스 객체 생성
    2. 생성자 배열에 있는 모든 생성자의 모든 메타데이터 가져오기
    3. Guru99Constructor.class 클래스에 있는 모든 생성자의 이름을 출력합니다.
    4. Guru99Constructor.class 클래스에 있는 생성자의 모든 액세스 수정자를 인쇄했습니다.
    5. Guru99Constructor.class에 있는 생성자의 인쇄된 매개변수 유형
    6. 인쇄된 예외는 Guru99Constructor.class의 생성자에 의해 발생합니다.

    요약:


    java

    1. 자바 익명 클래스
    2. 자바 리플렉션
    3. 자바 ObjectInputStream 클래스
    4. 자바 ObjectOutputStream 클래스
    5. 예제가 있는 C++ 클래스 및 개체
    6. C# 추상 클래스 자습서 예제:추상화란?
    7. 예제가 있는 Java 문자열 charAt() 메서드
    8. 예제가 포함된 Java 문자열 endWith() 메서드
    9. Java BufferedReader:예제를 사용하여 Java에서 파일을 읽는 방법
    10. 프로그램 예제가 있는 Java의 삽입 정렬 알고리즘