У овом упутству научићемо рефлексију, функцију у Јава програмирању која нам омогућава да прегледамо и модификујемо класе, методе итд.
У Јави, рефлексија нам омогућава преглед и манипулисање класама, интерфејсима, конструкторима, методама и пољима током извођења.
У Јава постоји класа Class
која чува све информације о објектима и класама током извођења. Објекат класе се може користити за извођење рефлексије.
Одраз Јава класа
Да бисмо одражавали Јава класу, прво треба да креирамо објекат Цласс.
И, користећи објекат, можемо позвати различите методе да бисмо добили информације о методама, пољима и конструкторима присутним у класи.
Постоје три начина за стварање објеката класе:
1. Коришћењем форНаме () методе
class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");
Овде forName()
метода узима назив класе да би се одразило као њен аргумент.
2. Коришћењем методе гетЦласс ()
// create an object of Dog class Dog d1 = new Dog(); // create an object of Class // to reflect Dog Class b = d1.getClass();
Овде користимо објекат класе Дог да бисмо креирали објекат класе.
3. Коришћење екстензије .цласс
// create an object of Class // to reflect the Dog class Class c = Dog.class;
Сада када знамо како можемо да направимо објекте Class
. Овим објектом можемо да користимо информације о одговарајућој класи током извођења.
Пример: Јава Цласс Рефлецтион
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(); ) ) )
Оутпут
Име: Модификатор пса: јавни Суперкласа: Животиња
У горњем примеру створили смо суперкласу: Животиња и поткласу: Пас. Овде покушавамо да прегледамо разред Пса.
Обратите пажњу на изјаву,
Class obj = d1.getClass();
Овде креирамо објекат обј од Цласс користећи getClass()
методу. Користећи објекат, позивамо различите методе класе.
- обј.гетНаме () - враћа име класе
- обј.гетМодифиерс () - враћа модификатор приступа класи
- обј.гетСуперцласс () - враћа супер класу класе
Да бисте сазнали више о томе Class
, посетите Јава Цласс (званична Јава документација).
Напомена : Modifier
Класу користимо за претварање целобројног модификатора приступа у низ.
Одражавање поља, метода и конструктора
Пакет java.lang.reflect
пружа класе које се могу користити за манипулисање члановима класе. На пример,
- Класа метода - пружа информације о методама у класи
- Класа поља - пружа информације о пољима у класи
- Класа конструктора - пружа информације о конструкторима у класи
1. Рефлексија Јава метода
Method
Класа предвиђа различите методе које се могу користити да би добили информације о представљеним поступцима у класи. На пример,
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(); ) ) )
Оутпут
Назив методе: дисплаи Модифиер: публиц Типови поврата: воид Назив методе: макеСоунд Модифиер: привате Типови поврата: воид
У горњем примеру покушавамо да добијемо информације о методама присутним у класи Пас. Као што је раније поменуто, прво смо креирали објекат обј Class
користећи getClass()
методу.
Примети израз,
Method() methods = obj.getDeclaredMethod();
Овде getDeclaredMethod()
враћа све методе присутне унутар класе.
Такође смо креирали објекат м Method
класе. Ево,
- м.гетНаме () - враћа име методе
- м.гетМодифиерс () - враћа модификатор приступа методама у целобројном облику
- м.гетРетурнТипе () - враћа тип метода повратка
Method
Класа такође обезбеђује разне друге методе које се могу користити за инспекцију методе у рун времена. Да бисте сазнали више, посетите класу Јава метода (званична Јава документација).
2. Одраз Јава поља
Као и методе, такође можемо да прегледамо и модификујемо различита поља класе користећи методе Field
класе. На пример,
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(); ) ) )
Оутпут
Вредност: лабрадор Модификатор: јавни
У горњем примеру створили смо класу Пас. Садржи јавно поље са именом типа. Обратите пажњу на изјаву,
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();
Овде приступамо свим конструкторима присутним у Дог-у и додељујемо их конструкторима низа Constructor
типа.
Затим смо користили објекат ц да бисмо добили различите информације о конструктору.
- ц.гетНаме () - враћа име конструктора
- ц.гетМодифиерс () - враћа модификаторе приступа конструктора у целобројном облику
- ц.гетПараметерЦоунт () - враћа број параметара присутних у сваком конструктору
Да бисте сазнали више о методама Constructor
класе, посетите класу Конструктор