Java Reflection (z przykładami)

W tym samouczku nauczymy się refleksji, funkcji programowania w Javie, która pozwala nam sprawdzać i modyfikować klasy, metody itp.

W Javie odbicie pozwala nam sprawdzać i manipulować klasami, interfejsami, konstruktorami, metodami i polami w czasie wykonywania.

W Javie istnieje klasa o nazwie, Classktóra przechowuje wszystkie informacje o obiektach i klasach w czasie wykonywania. Przedmiot klasy może służyć do refleksji.

Odbicie klas Java

Aby odzwierciedlić klasę Javy, najpierw musimy utworzyć obiekt klasy.

Korzystając z obiektu, możemy wywołać różne metody, aby uzyskać informacje o metodach, polach i konstruktorach obecnych w klasie.

Istnieją trzy sposoby tworzenia obiektów klasy:

1. Użycie metody forName ()

 class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");

Tutaj forName()metoda przyjmuje nazwę klasy, która ma być odzwierciedlona jako jej argument.

2. Za pomocą metody getClass ()

 // create an object of Dog class Dog d1 = new Dog(); // create an object of Class // to reflect Dog Class b = d1.getClass();

Tutaj używamy obiektu klasy Dog do tworzenia obiektu klasy.

3. Korzystanie z rozszerzenia .class

 // create an object of Class // to reflect the Dog class Class c = Dog.class;

Teraz, gdy wiemy, jak możemy tworzyć obiekty Class. Możemy użyć tego obiektu, aby uzyskać informacje o odpowiedniej klasie w czasie wykonywania.

Przykład: odbicie klasy 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(); ) ) )

Wynik

 Imię: Pies Modyfikator: publiczna Nadklasa: Zwierzę

W powyższym przykładzie utworzyliśmy nadklasę: Zwierzę i podklasę: Pies. Tutaj próbujemy sprawdzić klasę Dog.

Zwróć uwagę na oświadczenie,

 Class obj = d1.getClass();

Tutaj tworzymy obiekt obj klasy Class przy użyciu getClass()metody. Korzystając z obiektu, wywołujemy różne metody Class.

  • obj.getName () - zwraca nazwę klasy
  • obj.getModifiers () - zwraca modyfikator dostępu klasy
  • obj.getSuperclass () - zwraca superklasę klasy

Aby dowiedzieć się więcej Class, odwiedź stronę Java Class (oficjalna dokumentacja Java).

Uwaga : używamy tej Modifierklasy do konwersji modyfikatora dostępu w postaci liczb całkowitych na łańcuch.

Odzwierciedlanie pól, metod i konstruktorów

Pakiet java.lang.reflectzawiera klasy, których można używać do manipulowania składowymi klas. Na przykład,

  • Klasa metod - dostarcza informacji o metodach w klasie
  • Klasa pola - zawiera informacje o polach w klasie
  • Constructor class - dostarcza informacji o konstruktorach w klasie

1. Refleksja na temat metod języka Java

MethodKlasa dostarcza różnych metod, które można wykorzystać, aby uzyskać informacje na temat obecnych metod w klasie. Na przykład,

 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(); ) ) )

Wynik

 Nazwa metody: display Modyfikator: public Typy zwrotów: void Nazwa metody: make Modyfikator dźwięku: private Typy zwrotów: void

W powyższym przykładzie staramy się uzyskać informacje o metodach obecnych w klasie Dog. Jak wspomniano wcześniej, najpierw utworzyliśmy obiekt obj za Classpomocą getClass()metody.

Zwróć uwagę na wyrażenie,

 Method() methods = obj.getDeclaredMethod();

Tutaj getDeclaredMethod()zwraca wszystkie metody obecne w klasie.

Stworzyliśmy również obiekt m Methodklasy. Tutaj,

  • m.getName () - zwraca nazwę metody
  • m.getModifiers () - zwraca modyfikator dostępu do metod w postaci liczb całkowitych
  • m.getReturnType () - zwraca zwracany typ metod

MethodKlasa zapewnia również różne inne metody, które mogą być wykorzystane do kontroli metod w czasie wykonywania. Aby dowiedzieć się więcej, odwiedź klasę metody Java (oficjalna dokumentacja języka Java).

2. Odbicie pól Java

Podobnie jak metody, możemy również sprawdzać i modyfikować różne pola klasy przy użyciu metod Fieldklasy. Na przykład,

 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(); ) ) )

Wynik

 Wartość: labrador Modyfikator: publiczny

W powyższym przykładzie utworzyliśmy klasę o nazwie Dog. Zawiera pole publiczne o nazwie type. Zwróć uwagę na oświadczenie,

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

Tutaj uzyskujemy dostęp do pola publicznego klasy Dog i przypisujemy je do obiektu field1 klasy Field.

Następnie zastosowaliśmy różne metody Fieldklasy:

  • field1.set () - ustawia wartość pola
  • field1.get () - zwraca wartość pola
  • field1.getModifiers () - zwraca wartość pola w postaci liczby całkowitej

Podobnie możemy również uzyskać dostęp do pól prywatnych i je modyfikować. Jednak odbicie pola prywatnego różni się nieco od pola publicznego. Na przykład,

 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(); ) ) )

Wynik

 Wartość: brązowy Modyfikator: prywatny

W powyższym przykładzie utworzyliśmy klasę o nazwie Dog. Klasa zawiera prywatne pole o nazwie color. Zwróć uwagę na oświadczenie.

 Field field1 = obj.getDeclaredField("color"); field1.setAccessible(true);

Here, we are accessing color and assigning it to the object field1 of the Field class. We then used field1 to modify the accessibility of color and allows us to make changes to it.

We then used field1 to perform various operations on the private field color.

To learn more about the different methods of Field, visit Java Field Class (official Java documentation).

3. Reflection of Java Constructor

We can also inspect different constructors of a class using various methods provided by the Constructor class. For example,

 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(); ) ) )

Output

 Constructor Name: Dog Modifier: public Parameters: 0 Constructor Name: Dog Modifier: private Parameters: 1

In the above example, we have created a class named Dog. The class includes two constructors.

We are using reflection to find the information about the constructors of the class. Notice the statement,

 Constructor() constructors = obj.getDeclaredConstructor();

Tutaj uzyskujemy dostęp do wszystkich konstruktorów obecnych w Dog i przypisujemy je do konstruktorów tablicy tego Constructortypu.

Następnie użyliśmy obiektu c, aby uzyskać różne informacje o konstruktorze.

  • c.getName () - zwraca nazwę konstruktora
  • c.getModifiers () - zwraca modyfikatory dostępu konstruktora w postaci liczby całkowitej
  • c.getParameterCount () - zwraca liczbę parametrów obecnych w każdym konstruktorze

Aby dowiedzieć się więcej o metodach tej Constructorklasy, odwiedź klasę Constructor

Interesujące artykuły...