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

자바 리플렉션

자바 리플렉션

이 자습서에서는 클래스, 메서드 등을 검사하고 수정할 수 있는 Java 프로그래밍 기능인 리플렉션을 배웁니다.

자바에서 리플렉션을 사용하면 런타임에 클래스, 인터페이스, 생성자, 메서드 및 필드를 검사하고 조작할 수 있습니다.

Java에 Class라는 클래스가 있습니다. 런타임에 개체 및 클래스에 대한 모든 정보를 유지합니다. 클래스의 객체 반사를 수행하는 데 사용할 수 있습니다.

<시간>

자바 클래스 반영

Java 클래스를 반영하려면 먼저 Class 객체를 생성해야 합니다. .

또한 객체를 사용하여 다양한 메서드를 호출하여 클래스에 있는 메서드, 필드 및 생성자에 대한 정보를 얻을 수 있습니다.

클래스의 개체를 만드는 세 가지 방법이 있습니다.

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 객체를 생성하는 방법을 알게 되었습니다. . 이 객체를 사용하여 런타임에 해당 클래스에 대한 정보를 얻을 수 있습니다.

<시간>

예:자바 클래스 반영

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의 다른 메서드를 호출합니다. .

Class에 대해 자세히 알아보려면 , Java 클래스(공식 Java 문서)를 방문하십시오.

참고 :Modifier을 사용하고 있습니다. 정수 액세스 수정자를 문자열로 변환하는 클래스입니다.

<시간>

필드, 메소드 및 생성자 반영

패키지 java.lang.reflect 클래스 멤버를 조작하는 데 사용할 수 있는 클래스를 제공합니다. 예를 들어,

<시간>

1. 자바 메소드 반영

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 객체를 생성했습니다. ClassgetClass() 사용 방법.

표현에 주목하세요.

Method[] methods = obj.getDeclaredMethod();

여기에서 getDeclaredMethod() 클래스 내부에 있는 모든 메서드를 반환합니다.

또한 m 객체를 생성했습니다. Method 수업. 여기,

Method 클래스는 런타임에 메서드를 검사하는 데 사용할 수 있는 다양한 다른 메서드도 제공합니다. 자세한 내용은 Java Method 클래스(공식 Java 설명서)를 참조하십시오.

<시간>

2. 자바 필드 반영

메서드와 마찬가지로 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이라는 공개 필드가 포함됩니다. . 진술을 주목하십시오.

Field field1 = obj.getField("type");

여기에서 Dog의 공개 필드에 액세스하고 있습니다. 클래스 및 개체 field1에 할당 필드 수업.

그런 다음 Field 클래스:

마찬가지로 개인 필드에도 액세스하고 수정할 수 있습니다. 그러나 사적 영역의 반영은 공적 영역과 조금 다릅니다. 예를 들어,

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을 사용하여 private 필드 색상에 대해 다양한 작업을 수행했습니다.

Field의 다양한 메서드에 대해 자세히 알아보려면 , Java Field Class(공식 Java 문서)를 방문하십시오.

<시간>

3. 자바 생성자의 반영

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라는 클래스를 만들었습니다. . 클래스에는 두 개의 생성자가 포함됩니다.

우리는 리플렉션을 사용하여 클래스의 생성자에 대한 정보를 찾습니다. 진술을 주목하십시오.

Constructor[] constructors = obj.getDeclaredConstructor();

여기에서는 Dog에 있는 모든 생성자에 액세스합니다. 배열 생성자에 할당 Constructor 유형.

그런 다음 c 개체를 사용했습니다. 생성자에 대한 다양한 정보를 얻을 수 있습니다.

Constructor의 더 많은 방법에 대해 알아보려면 클래스, 생성자 클래스 방문


java

  1. 자바 최종 키워드
  2. 자바 instanceof 연산자
  3. 자바 상속
  4. 자바 중첩 정적 클래스
  5. 자바 익명 클래스
  6. 자바 싱글톤 클래스
  7. 자바 ArrayList 클래스
  8. 자바 ObjectOutputStream 클래스
  9. 자바 제네릭
  10. 자바 파일 클래스