V tomto tutoriálu se naučíme reflexi, funkci v programování Java, která nám umožňuje kontrolovat a upravovat třídy, metody atd.
V Javě nám reflexe umožňuje kontrolovat a manipulovat s třídami, rozhraními, konstruktory, metodami a poli za běhu.
V Javě existuje třída s názvem, Class
která uchovává všechny informace o objektech a třídách za běhu. Objekt třídy lze použít k provedení odrazu.
Reflexe tříd Java
Abychom odráželi třídu Java, musíme nejprve vytvořit objekt třídy.
A pomocí objektu můžeme volat různé metody, abychom získali informace o metodách, polích a konstruktorech přítomných ve třídě.
Existují tři způsoby, jak vytvořit objekty třídy:
1. Použití metody forName ()
class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");
Zde forName()
metoda přebírá název třídy, aby se projevila jako její argument.
2. 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();
Tady používáme objekt třídy Dog k vytvoření objektu třídy.
3. Použití rozšíření .class
// create an object of Class // to reflect the Dog class Class c = Dog.class;
Nyní, když víme, jak můžeme vytvářet objekty Class
. Tento objekt můžeme použít k získání informací o odpovídající třídě za běhu.
Příklad: Java Class Reflection
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(); ) ) )
Výstup
Název: Modifikátor psa: veřejná Nadtřída: Zvíře
Ve výše uvedeném příkladu jsme vytvořili nadtřídu: Zvíře a podtřídu: Pes. Tady se snažíme zkontrolovat třídu Pes.
Všimněte si prohlášení,
Class obj = d1.getClass();
Zde pomocí getClass()
metody vytváříme objekt obj třídy . Pomocí objektu voláme různé metody třídy.
- obj.getName () - vrátí název třídy
- obj.getModifiers () - vrací modifikátor přístupu třídy
- obj.getSuperclass () - vrací super třídu třídy
Další informace Class
najdete na stránce Java Class (oficiální dokumentace Java).
Poznámka : Modifier
Třídu používáme k převodu modifikátoru přístupu k celému číslu na řetězec.
Odráží pole, metody a konstruktory
Balíček java.lang.reflect
poskytuje třídy, které lze použít pro manipulaci s členy třídy. Například,
- Třída metody - poskytuje informace o metodách ve třídě
- Polní třída - poskytuje informace o polích ve třídě
- Třída konstruktoru - poskytuje informace o konstruktorech ve třídě
1. Reflexe metod Java
Method
Třída poskytuje různé metody, které lze použít k získání informací o současných metod ve třídě. Například,
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(); ) ) )
Výstup
Název metody: modifikátor zobrazení: veřejné Typy návratů: neplatné Název metody: modifikátor makeSound: soukromé Typy návratů: neplatné
Ve výše uvedeném příkladu se snažíme získat informace o metodách přítomných ve třídě Dog. Jak již bylo zmíněno dříve, nejprve jsme Class
pomocí getClass()
metody vytvořili objekt obj .
Všimněte si výrazu,
Method() methods = obj.getDeclaredMethod();
Zde getDeclaredMethod()
vrací všechny metody přítomné uvnitř třídy.
Také jsme vytvořili objekt m Method
třídy. Tady,
- m.getName () - vrací název metody
- m.getModifiers () - vrací modifikátor přístupu metod v celočíselném tvaru
- m.getReturnType () - vrací návratový typ metod
Method
Třída také poskytuje různé jiné způsoby, které mohou být použity pro kontrolu metody na běhu. Další informace najdete ve třídě Java Method (oficiální dokumentace Java).
2. Odraz Java polí
Stejně jako metody můžeme také kontrolovat a upravovat různá pole třídy pomocí metod Field
třídy. Například,
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(); ) ) )
Výstup
Hodnota: labrador Modifikátor: veřejný
Ve výše uvedeném příkladu jsme vytvořili třídu s názvem Dog. Zahrnuje veřejné pole s názvem typ. Všimněte si prohlášení,
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();
Zde přistupujeme ke všem konstruktorům přítomným v Dogu a přiřazujeme je konstruktorům pole Constructor
typu.
Poté jsme použili objekt c k získání různých informací o konstruktoru.
- c.getName () - vrací název konstruktoru
- c.getModifiers () - vrací modifikátory přístupu konstruktoru v celočíselném tvaru
- c.getParameterCount () - vrací počet parametrů přítomných v každém konstruktoru
Chcete-li se dozvědět více metod Constructor
třídy, navštivte třídu Constructor