V tej vadnici se bomo naučili refleksije, funkcije v programiranju Java, ki nam omogoča pregled in spreminjanje razredov, metod itd.
V Javi nam refleksija omogoča pregledovanje in upravljanje razredov, vmesnikov, konstruktorjev, metod in polj v času izvajanja.
V Javi obstaja razred, Class
ki hrani vse informacije o predmetih in razredih med izvajanjem. Predmet razreda lahko uporabimo za refleksijo.
Razmislek o razredih Java
Da bi odražali razred Java, moramo najprej ustvariti objekt razreda.
In z uporabo predmeta lahko pokličemo različne metode, da dobimo informacije o metodah, poljih in konstruktorjih, prisotnih v razredu.
Obstajajo trije načini za ustvarjanje predmetov razreda:
1. Uporaba metode forName ()
class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");
Tu forName()
metoda uporablja kot argument ime razreda, ki se odraža kot njen argument.
2. Uporaba metode getClass ()
// create an object of Dog class Dog d1 = new Dog(); // create an object of Class // to reflect Dog Class b = d1.getClass();
Tu uporabljamo objekt razreda Dog za ustvarjanje predmeta razreda.
3. Uporaba razširitve .class
// create an object of Class // to reflect the Dog class Class c = Dog.class;
Zdaj, ko vemo, kako lahko ustvarimo predmete Class
. Ta objekt lahko uporabimo za pridobivanje informacij o ustreznem razredu med izvajanjem.
Primer: 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(); ) ) )
Izhod
Ime: Modifikator psa: javni Superclass: Žival
V zgornjem primeru smo ustvarili superrazred: Žival in podrazred: Pes. Tu poskušamo pregledati razred Psa.
Upoštevajte izjavo,
Class obj = d1.getClass();
Tu ustvarjamo objekt obj razreda z uporabo getClass()
metode. Z uporabo predmeta pokličemo različne metode razreda.
- obj.getName () - vrne ime razreda
- obj.getModifiers () - vrne modifikator dostopa do razreda
- obj.getSuperclass () - vrne super razred razreda
Če želite izvedeti več o tem Class
, obiščite razred Java (uradna dokumentacija Java).
Opomba : Modifier
Razred uporabljamo za pretvorbo celovitega modifikatorja dostopa v niz.
Odsevajoča polja, metode in konstruktorji
Paket java.lang.reflect
vsebuje razrede, ki se lahko uporabljajo za manipulacijo s člani predavanja. Na primer
- Razred metode - zagotavlja informacije o metodah v razredu
- Razred polja - vsebuje informacije o poljih v razredu
- Razred konstruktorja - vsebuje informacije o konstruktorjih v razredu
1. Razmislek o Java metodah
Method
Razred določa različne metode, ki jih je mogoče uporabiti, da bi dobili informacije o metodah trenutno v razredu. Na primer
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(); ) ) )
Izhod
Ime metode: modifikator zaslona: javni Tipi vrnitve: void Ime metode: makeSound Modifikator: zasebni Tipi vrnitve: void
V zgornjem primeru poskušamo pridobiti informacije o metodah, ki so prisotne v razredu Dog. Kot smo že omenili, smo najprej ustvarili objekt obj z Class
uporabo getClass()
metode.
Upoštevajte izraz,
Method() methods = obj.getDeclaredMethod();
Tu getDeclaredMethod()
vrne vse metode, prisotne v razredu.
Ustvarili smo tudi objekt m Method
razreda. Tukaj,
- m.getName () - vrne ime metode
- m.getModifiers () - vrne modifikator dostopa metod v celoštevilčni obliki
- m.getReturnType () - vrne vrnjeno vrsto metod
Method
Razred določa tudi različne druge metode, ki se lahko uporabljajo za pregledovanje metode pri času čas. Če želite izvedeti več, obiščite razred metode Java (uradna dokumentacija Java).
2. Odsev polj Java
Tako kot metode lahko tudi z uporabo metod Field
razreda pregledamo in spremenimo različna polja razreda. Na primer
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(); ) ) )
Izhod
Vrednost: labrador Modifikator: javni
V zgornjem primeru smo ustvarili razred z imenom Dog. Vključuje javno polje z imenom type. Upoštevajte izjavo,
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();
Tukaj dostopamo do vseh konstruktorjev, ki so prisotni v pasu, in jih dodelimo nizom konstruktorjev Constructor
tipa.
Nato smo uporabili objekt c, da smo dobili različne informacije o konstruktorju.
- c.getName () - vrne ime konstruktorja
- c.getModifiers () - vrne modifikatorje dostopa konstruktorja v celoštevilčni obliki
- c.getParameterCount () - vrne število parametrov, prisotnih v vsakem konstruktorju
Če želite izvedeti več o metodah Constructor
predavanja, obiščite razred Constructor