V tomto tutoriále sa naučíme reflexiu, funkciu v programovaní Java, ktorá nám umožňuje kontrolovať a upravovať triedy, metódy atď.
V Jave nám reflexia umožňuje kontrolovať a manipulovať s triedami, rozhraniami, konštruktormi, metódami a poľami za behu.
V Jave je pomenovaná trieda, Class
ktorá uchováva všetky informácie o objektoch a triedach za behu. Objekt triedy je možné použiť na uskutočnenie odrazu.
Reflexia tried Java
Aby sme odrážali triedu Java, je potrebné najskôr vytvoriť objekt triedy.
A pomocou objektu môžeme zavolať rôzne metódy na získanie informácií o metódach, poliach a konštruktoroch prítomných v triede.
Existujú tri spôsoby, ako vytvoriť objekty triedy:
1. Použitie metódy forName ()
class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");
Tu forName()
metóda vezme názov triedy, aby sa prejavila ako jej argument.
2. Pomocou metódy getClass ()
// create an object of Dog class Dog d1 = new Dog(); // create an object of Class // to reflect Dog Class b = d1.getClass();
Tu používame objekt triedy Dog na vytvorenie objektu triedy.
3. Používanie prípony .class
// create an object of Class // to reflect the Dog class Class c = Dog.class;
Teraz, keď vieme, ako môžeme vytvárať objekty Class
. Tento objekt môžeme použiť na získanie informácií o príslušnej triede za behu.
Príklad: Reflexia triedy 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(); ) ) )
Výkon
Názov: Pes Modifikátor: verejný Nadtrieda: Zviera
Vo vyššie uvedenom príklade sme vytvorili nadtriedu: Zviera a podtriedu: Pes. Tu sa snažíme skontrolovať triedu Pes.
Všimnite si vyhlásenie,
Class obj = d1.getClass();
Tu pomocou getClass()
metódy vytvárame objekt obj triedy . Pomocou objektu voláme rôzne metódy triedy.
- obj.getName () - vráti názov triedy
- obj.getModifiers () - vráti modifikátor prístupu triedy
- obj.getSuperclass () - vráti super triedu triedy
Ak sa chcete dozvedieť viac Class
, navštívte Java Class (oficiálna dokumentácia Java).
Poznámka : Modifier
Triedu používame na konverziu celočíselného modifikátora prístupu na reťazec.
Odrážajúce polia, metódy a konštruktory
Balík java.lang.reflect
poskytuje triedy, ktoré možno použiť na manipuláciu s členmi triedy. Napríklad,
- Trieda metód - poskytuje informácie o metódach v triede
- Trieda poľa - poskytuje informácie o poliach v triede
- Trieda konštruktora - poskytuje informácie o konštruktoroch v triede
1. Reflexia metód Java
Method
Trieda poskytuje rôzne metódy, ktoré možno použiť na získanie informácií o súčasných metód v triede. Naprí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ýkon
Názov metódy: modifikátor displeja: verejné Typy návratov: neplatné Názov metódy: modifikátor makeSound: súkromné Typy návratov: neplatné
V uvedenom príklade sa snažíme získať informácie o metódach prítomných v triede Pes. Ako už bolo spomenuté, najskôr sme Class
pomocou getClass()
metódy vytvorili objekt obj .
Všimnite si výraz,
Method() methods = obj.getDeclaredMethod();
Tu getDeclaredMethod()
vráti všetky metódy prítomné vo vnútri triedy.
Tiež sme vytvorili objekt m Method
triedy. Tu,
- m.getName () - vráti názov metódy
- m.getModifiers () - vráti modifikátor prístupu metód v celočíselnej podobe
- m.getReturnType () - vráti návratový typ metód
Method
Trieda tiež poskytuje rôzne iné spôsoby, ktoré môžu byť použité pre kontrolu metódy na behu. Ak sa chcete dozvedieť viac, navštívte triedu Java Method (oficiálna dokumentácia Java).
2. Odraz polí Java
Rovnako ako metódy, aj pomocou metód Field
triedy môžeme kontrolovať a upravovať rôzne polia triedy. Naprí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ýkon
Hodnota: labrador Modifikátor: verejný
Vo vyššie uvedenom príklade sme vytvorili triedu s názvom Pes. Zahŕňa verejné pole s názvom typ. Všimnite si vyhlásenie,
Field field1 = obj.getField("type");
Tu pristupujeme k verejnému poľu triedy Dog a priraďujeme ho k objektovému poľu1 triedy Field.
Potom sme použili rôzne metódy Field
triedy:
- field1.set () - nastavuje hodnotu poľa
- field1.get () - vráti hodnotu poľa
- field1.getModifiers () - vráti hodnotu poľa v celočíselnom tvare
Podobne môžeme tiež pristupovať a upravovať súkromné polia. Odraz súkromného poľa sa však trochu líši od verejného poľa. Napríklad,
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(); ) ) )
Výkon
Hodnota: hnedá Modifikátor: súkromný
Vo vyššie uvedenom príklade sme vytvorili triedu s názvom Pes. Trieda obsahuje súkromné pole s názvom color. Všimnite si vyhlásenie.
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();
Tu pristupujeme ku všetkým konštruktorom prítomným v Doge a priraďujeme ich konštruktorom poľa Constructor
typu.
Potom sme použili objekt c na získanie rôznych informácií o konštruktore.
- c.getName () - vráti meno konštruktora
- c.getModifiers () - vráti modifikátory prístupu konštruktora v celočíselnom tvare
- c.getParameterCount () - vráti počet parametrov prítomných v každom konštruktore
Ak sa chcete dozvedieť viac metód Constructor
triedy, navštívte triedu Constructor