Java reflexió (példákkal)

Ebben az oktatóanyagban megtanuljuk a reflektálást, a Java programozás egyik olyan funkcióját, amely lehetővé teszi számunkra az osztályok, módszerek stb. Ellenőrzését és módosítását.

A Java-ban a reflexió lehetővé teszi számunkra az osztályok, interfészek, konstruktorok, módszerek és mezők futási időben történő ellenőrzését és manipulálását.

Van egy Java nevű Classosztály, amely futás közben megőrzi az objektumokról és osztályokról szóló összes információt. A Class objektuma felhasználható reflexió végrehajtására.

Java osztályok tükrözése

A Java osztály tükrözése érdekében először létre kell hoznunk egy Class objektumot.

Az objektum segítségével különféle módszereket hívhatunk meg, hogy információkat szerezzünk az osztályban jelen lévő módszerekről, mezőkről és konstruktorokról.

Három módja van a Class objektumok létrehozásának:

1. A forName () metódus használata

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

Itt a forName()módszer az osztály nevét tükrözi argumentumként.

2. A getClass () metódus használata

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

Itt a Dog osztály objektumát használjuk a Class objektum létrehozásához.

3. .class kiterjesztés használata

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

Most, hogy tudjuk, hogyan hozhatunk létre a Class. Használhatjuk ezt az objektumot arra, hogy futás közben információkat szerezzünk a megfelelő osztályról.

Példa: Java osztály reflexió

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

Kimenet

 Név: Kutya módosító: nyilvános szuperosztály: állat

A fenti példában létrehoztunk egy szuperosztályt: Animal és egy alosztályt: Dog. Itt megpróbáljuk megvizsgálni a kutyát.

Figyelje meg az állítást,

 Class obj = d1.getClass();

Itt a Class objektum objektumot hozunk létre a getClass()módszer segítségével. Az objektum használatával különböző Class módszereket hívunk meg.

  • obj.getName () - az osztály nevét adja vissza
  • obj.getModifiers () - az osztály hozzáférés-módosítóját adja vissza
  • obj.getSuperclass () - az osztály szuper osztályát adja vissza

További információért Classlátogasson el a Java osztályra (hivatalos Java dokumentáció).

Megjegyzés : Az Modifierosztály segítségével konvertáljuk az egész hozzáférés módosítót karakterlánccá.

Reflektáló mezők, módszerek és konstruktorok

A csomag java.lang.reflectolyan osztályokat tartalmaz, amelyek felhasználhatók az osztálytagok manipulálására. Például,

  • Metód osztály - információkat nyújt az osztály metódusairól
  • Terepi osztály - információkat nyújt az osztály mezõiről
  • Konstruktor osztály - információt nyújt egy osztály konstruktőreiről

1. A Java módszerek tükrözése

Az Methodosztály különféle módszereket kínál, amelyekkel információkat lehet szerezni az osztályban jelenlévő módszerekről. Például,

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

Kimenet

 Módszer neve: display Módosító: public Visszatérés típusok: void Módszer neve: makeSound Módosító: privát Vissza típusok: érvénytelen

A fenti példában megpróbálunk információt szerezni a Kutya osztályban alkalmazott módszerekről. Mint korábban említettük, először létrehoztunk egy objektum objektumot Classa getClass()módszer használatával.

Figyelje meg a kifejezést,

 Method() methods = obj.getDeclaredMethod();

Itt getDeclaredMethod()az osztályon belüli összes metódust adja vissza.

Hoztunk létre egy objektumot is az Methodosztályból. Itt,

  • m.getName () - egy metódus nevét adja vissza
  • m.getModifiers () - a metódusok hozzáférés-módosítóját adja vissza egész számban
  • m.getReturnType () - a metódusok visszatérési típusát adja vissza

Az Methodosztály különféle egyéb módszereket is kínál, amelyek felhasználhatók a módszerek futási időben történő ellenőrzésére. További információkért látogasson el a Java Method osztályba (hivatalos Java dokumentáció).

2. Java mezők tükrözése

A módszerekhez hasonlóan az Fieldosztály módszereit is megvizsgálhatjuk és módosíthatjuk az osztály különböző területein . Például,

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

Kimenet

 Érték: labrador Módosító: nyilvános

A fenti példában létrehoztunk egy Dog nevű osztályt. Típusú nyilvános mezőt tartalmaz. Figyelje meg az állítást,

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

Here, we are accessing the public field of the Dog class and assigning it to the object field1 of the Field class.

We then used various methods of the Field class:

  • field1.set() - sets the value of the field
  • field1.get() - returns the value of field
  • field1.getModifiers() - returns the value of the field in integer form

Similarly, we can also access and modify private fields as well. However, the reflection of private field is little bit different than the public field. For example,

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

Output

 Value: brown Modifier: private

In the above example, we have created a class named Dog. The class contains a private field named color. Notice the statement.

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

Itt a Dog összes konstruktorához hozzáférünk, és hozzárendeljük őket egy Constructorilyen típusú tömb konstruktorhoz .

Ezután a c objektum segítségével különböző információkat kaptunk a konstruktorról.

  • c.getName () - a konstruktor nevét adja vissza
  • c.getModifiers () - a konstruktor hozzáférés-módosítóit egész alakban adja vissza
  • c.getParameterCount () - az egyes konstruktorokban jelen lévő paraméterek számát adja vissza

Az Constructorosztály további módszereiről a Konstruktor osztályban tájékozódhat

érdekes cikkek...