Java Samouczek API Reflection z przykładem
W czym jest odbicie Java?
Java Refleksja to proces analizowania i modyfikowania wszystkich możliwości klasy w czasie wykonywania. Odbicie API w Java służy do manipulowania klasą i jej elementami, które obejmują pola, metody, konstruktory itp. w czasie wykonywania.
Jedną z zalet refleksji API w Java oznacza to, że może manipulować także prywatnymi członkami klasy.
Pakiet java.lang.reflect udostępnia wiele klas umożliwiających implementację refleksji. Metody java.Methods klasy java.lang.Class służą do gromadzenia pełnych metadanych określonej klasy.
Klasa w pakiecie java.lang.reflect
Poniżej znajduje się lista różnorodny Java Klasy w java.lang.package, aby zaimplementować odbicie-
- Pole: Ta klasa służy do zbierania informacji deklaratywnych, takich jak typ danych, modyfikator dostępu, nazwa i wartość zmiennej.
- Metoda wykonania: Ta klasa służy do zbierania informacji deklaratywnych, takich jak modyfikator dostępu, typ zwracany, nazwa, typy parametrów i typ wyjątku metody.
- Konstruktor: Ta klasa służy do zbierania informacji deklaratywnych, takich jak modyfikator dostępu, nazwa i typy parametrów konstruktora.
- zmiana: Ta klasa służy do zbierania informacji o konkretnym modyfikatorze dostępu.
Metody stosowane w java.lang.Class
- Publiczny ciąg znaków getName (): Zwraca nazwę klasy.
- Klasa publiczna getSuperclass(): Zwraca odwołanie do superklasy
- Klasa publiczna[] getInterfaces() : Zwraca tablicę interfejsów zaimplementowanych przez określoną klasę
-
Publiczne w getModifiers (): Zwraca wartość całkowitą reprezentującą modyfikatory określonej klasy, która musi zostać przekazana jako parametr do „publiczny statyczny ciąg znaków toString (int i )” metoda zwracająca specyfikator dostępu dla danej klasy.
Jak uzyskać pełne informacje o klasie
public class Guru99ClassObjectCreation {
public static void main (String[] args) throws ClassNotFoundException {
//1 - By using Class.forname() method
Class c1 = Class.forName("Guru99ClassObjectCreation");
//2- By using getClass() method
Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation();
Class c2 = guru99Obj.getClass();
//3- By using .class
Class c3= Guru99ClassObjectCreation.class;
}
}
Przykład 1: Jak uzyskać metadane klasy
Poniższy przykład pokazuje, jak uzyskać metadane, takie jak: nazwa klasy, nazwa superklasy, zaimplementowane interfejsy i modyfikatory dostępu do klasy.
Otrzymamy metadane poniższej klasy o nazwie Guru99Base.class:
import java.io.Serializable;
public abstract class Guru99Base implements Serializable,Cloneable {
}
- Nazwa klasy to: Guru99Base
- Jego modyfikatory dostępu to: publiczny i abstrakcyjny
- Posiada zaimplementowane interfejsy: Serializable i Cloneable
- Ponieważ nie rozszerzyła jawnie żadnej klasy, jej superklasą jest: java.lang.Object
Poniższa klasa pobierze metadane Guru99Base.class i wydrukuje je:
import java.lang.reflect.Modifier;
public class Guru99GetclassMetaData {
public static void main (String [] args) throws ClassNotFoundException {
// Create Class object for Guru99Base.class
Class guru99ClassObj = Guru99Base.class;
// Print name of the class
system.out.println("Name of the class is : " +guru99ClassObj.getName());
// Print Super class name
system.out.println("Name of the super class is : " +guru99ClassObj.getSuperclass().getName());
// Get the list of implemented interfaces in the form of Class array using getInterface() method
class[] guru99InterfaceList = guru99classObj.getInterfaces();
// Print the implemented interfaces using foreach loop
system.out.print("Implemented interfaces are : ");
for (Class guru99class1 : quru99 InterfaceList) {
system.out.print guru99class1.getName() + " ");
}
system.out.println();
//Get access modifiers using get Modifiers() method and toString() method of java.lang.reflect.Modifier class
int guru99AccessModifier= guru99classObj.getModifiers();
// Print the access modifiers
System.Out.println("Access modifiers of the class are : " +Modifier.tostring(guru99AccessModifier));
}
}
- wydrukuj nazwę klasy za pomocą metody getName
- Wydrukuj nazwę superklasy za pomocą metody getSuperClass().getName().
- Wydrukuj nazwę zaimplementowanych interfejsów
- Wydrukuj modyfikatory dostępu używane przez klasę
Przykład 2: Jak uzyskać metadane zmiennej
Poniższy przykład pokazuje, jak uzyskać metadane zmiennej:
Tutaj tworzymy klasę o nazwie Guru99VariableMetaData .class z kilkoma zmiennymi:
package guru;
public class Guru99VariableMetaData {
public static int guru99IntVar1=1111;
static int guru99IntVar2=2222;
static String guru99StringVar1="guru99.com";
static String guru99StringVar2="Learning Reflection API";
}
-
Utwórz obiekt klasy powyższej klasy, tj. Guru99VariableMetaData.class jak poniżej:
Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass();
-
Uzyskaj metadane w postaci tablicy pól za pomocą getFields() or getDeclaredFields() metody jak poniżej:
Field[] guru99Field1= guru99ClassObjVar .getFields(); Field[] guru99Fiel2= guru99ClassObjVar .getDeclaredFields();
getFields() metoda zwraca metadane zmiennej publicznej z określonej klasy, a także z jej nadklasy.
getDeclaredFields() Metoda zwraca metadane tylko wszystkich zmiennych z określonej klasy.
- Uzyskaj nazwę zmiennych za pomocą metody „public String getName()”.
- Uzyskaj typ danych zmiennych za pomocą metody „public Class getType()”.
-
Uzyskaj wartość zmiennej za pomocą metody „public xxx get (Field)”.
W tym przypadku xxx może oznaczać bajt lub dowolną wartość, którą chcemy pobrać.
-
Uzyskaj modyfikatory dostępu do zmiennych za pomocą metod getModifier() i Modifier.toString(int i).
Tutaj piszemy klasę, aby uzyskać metadane zmiennych obecnych w klasie Guru99VariableMetaData .class:
package guru; import java.lang.reflect.Field; public class Guru99VariableMetaDataTest { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { // Create Class object for Guru99VariableMetaData.class Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass(); // Get the metadata of all the fields of the class Guru99VariableMetaData Field[] guru99Field1= guru99ClassObjVar.getDeclaredFields(); // Print name, datatypes, access modifiers and values of the varibales of the specified class for(Field field : guru99Field1) { System.out.println("Variable name : "+field.getName()); System.out.println("Datatypes of the variable :"+field.getType()); int guru99AccessModifiers = field.getModifiers(); System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(guru99AccessModifiers)); System.out.println("Value of the variable : "+field.get(guru99ClassVar)); System.out.println(); system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ; } } } - Utworzono obiekt klasy dla Guru99VariableMetaData.class
- Mam wszystkie metadane zmiennych w tablicy Field
- Wydrukowano wszystkie nazwy zmiennych w klasie Guru99VariableMetaData.class
- Wydrukowano wszystkie typy danych zmiennych w klasie Guru99VariableMetaData.class
- Wydrukowano wszystkie modyfikatory dostępu do zmiennych w klasie Guru99VariableMetaData.class
- Wydrukowano wartości wszystkich zmiennych w Wydrukowano wszystkie typy danych zmiennych w klasie Guru99VariableMetaData.class
-
Utwórz obiekt klasy powyższej klasy, tj. Guru99MethodMetaData.class jak poniżej:
Guru99MethodMetaData guru99ClassVar = new Guru99MethodMetaData (); Class guru99ClassObjVar = guru99ClassVar.getClass();
-
Uzyskaj informacje o metodzie w tablicy metod za pomocą metod getMethods() i getDeclaredMethods() jak poniżej:
Method[] guru99 Method 1= guru99ClassObjVar .get Methods(); Method [] guru99 Method 2= guru99ClassObjVar .getDeclared Method s();
getMethods() metoda zwraca metadane metod publicznych z określonej klasy, a także z jej nadklasy.
getDeclaredMethods() metoda zwraca metadane tylko wszystkich metod z określonej klasy.
- Uzyskaj nazwę metody za pomocą getName () Metoda.
- Uzyskaj typ zwracany metody za pomocą getReturnType() Metoda.
- Uzyskaj modyfikatory dostępu metod używających getModifiers() oraz Modyfikatory.toString(int i) Metody.
- Pobierz typy parametrów metody za pomocą getParameterTypes() metoda zwracająca tablicę klas.
-
Uzyskaj zgłoszony wyjątek za pomocą getExceptionTypes() metoda zwracająca tablicę klas.
- Utworzono obiekt klasy dla Guru99MethodMetaData.class
- Mam wszystkie metadane wszystkich metod w tablicy metod
- Wydrukowano wszystkie nazwy metod obecne w klasie Guru99MethodMetaData.class
- Wydrukowane typy zwracanych metod z klasy Guru99MethodMetaData.class
- Wydrukowano wszystkie modyfikatory dostępu metod w klasie Guru99MethodMetaData.class
- Wydrukowane typy parametrów metod w Guru99MethodMetaData.class
-
Wydrukowane wyjątki są zgłaszane przez metody w Guru99MethodMetaData.class
- Utworzono obiekt klasy dla Guru99Constructor.class
- Mam wszystkie metadane wszystkich konstruktorów w tablicy Constructor
- Wydrukowano wszystkie nazwy konstruktorów obecne w klasie Guru99Constructor.class
- Wydrukowano wszystkie modyfikatory dostępu konstruktorów w klasie Guru99Constructor.class
- Wydrukowane typy parametrów konstruktorów w Guru99Constructor.class
- Drukowane wyjątki są zgłaszane przez konstruktory w klasie Guru99Constructor.class
- Programowanie refleksyjne w Javie pomaga w wyszukiwaniu i modyfikowaniu informacji o klasach i członkach klas, takich jak zmienne, metody, konstruktory.
- API refleksji w Java można zaimplementować za pomocą klas z pakietu java.lang.reflect i metod klasy java.lang.Class.
- Niektóre powszechnie używane metody klasy java.lang.Class to getName (), getSuperclass (), getInterfaces (), getModifiers () itp.
- Niektóre powszechnie używane klasy w pakiecie java.lang.reflect to pole, metoda, konstruktor, modyfikator itp.
- Reflection API może uzyskać dostęp do prywatnych metod i zmiennych klasy, które mogą stanowić zagrożenie bezpieczeństwa.
- Reflection API to potężna funkcja udostępniana przez Java, ale wiąże się z pewnymi kosztami, takimi jak wolniejsza wydajność, podatność na zagrożenia i problem z uprawnieniami. Dlatego też API refleksji powinno być traktowane jako ostateczność w wykonywaniu operacji.
Przykład 3: Jak uzyskać metadane metody
Poniższy przykład pokazuje, jak uzyskać metadane metody:
Tutaj tworzymy klasę o nazwie Guru99MethodMetaData .class z pewnymi metodami
package guru;
import java.sql.SQLException;
public class Guru99MethodMetaData {
public void guru99Add(int firstElement, int secondElement , String result)
throws ClassNotFoundException, ClassCastException{
System.out.println("Demo method for Reflextion API");
}
public String guru99Search(String searchString)
throws ArithmeticException, InterruptedException{
System.out.println("Demo method for Reflection API");
return null;
}
public void guru99Delete(String deleteString)
throws SQLException{
System.out.println("Demo method for Reflection API");
}
}
Kroki, aby uzyskać metadane dotyczące metod w powyższej klasie:
Tutaj piszemy klasę, aby uzyskać metadane metod występujących w klasie Guru99MethodMetaData.class:
package guru;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Guru99MethodMetaDataTest {
public static void main (String[] args) {
// Create Class object for Guru99Method MetaData.class
class guru99ClassObj = Guru99MethodMetaData.class;
// Get the metadata or information of all the methods of the class using getDeclaredMethods()
Method[] guru99Methods=guru99classObj.getDeclaredMethods();
for(Method method : guru99Methods) {
// Print the method names
System.out.println("Name of the method : "+method.getName());
// Print return type of the methods
System.out.println("Return type of the method : "+method.getReturnType());
//Get the access modifier list and print
int guru99ModifierList = method.getModifiers();
System.Out.printlin ("Method access modifiers : "+Modifier.toString(guru99ModifierList));
// Get and print parameters of the methods
Class[] guru99ParamList= method.getParameterTypes();
system.out.print ("Method parameter types : ");
for (Class class1 : guru99ParamList){
System.out.println(class1.getName()+" ");
}
System.out.println();
// Get and print exception thrown by the method
Class[] guru99ExceptionList = method. getExceptionTypes();
system.out.print("Excpetion thrown by method :");
for (Class class1 : guru99ExceptionList) {
System.out.println (class1.getName() +" "):
}
System.Out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ");
}
}
}
Przykład 4: Jak uzyskać metadane konstruktorów
Poniższe przykłady pokazują, jak uzyskać metadane konstruktorów:
Tutaj tworzymy klasę o nazwie Guru99Constructor.class z różnymi konstruktorami:
package guru;
import java.rmi.RemoteException;
import java.sql.SQLException;
public class Guru99Constructor {
public Guru99Constructor(int no) throws ClassCastException ,ArithmeticException{ }
public Guru99Constructor(int no, String name) throws RemoteException ,SQLException{ }
public Guru99Constructor(int no, String name, String address) throws InterruptedException{ }
}
Tutaj piszemy klasę, aby uzyskać metadane konstruktorów obecnych w klasie Guru99Constructor.class:
package guru;
import java.lang.reflect.Constructor;
public class Guru99ConstructorMetaDataTest {
public static void main (String[] args) {
// Create Class object for Guru99Constructor.class
Class guru99Class=Guru99Constructor.class;
// Get all the constructor information in the Constructor array
Constructor[] guru99ConstructorList = guru99Class.getConstructors();
for (Constructor constructor : guru99ConstructorList) {
// Print all name of each constructor
System.out.println("Constrcutor name : "+constructor.getName());
//Get and print access modifiers of each constructor
int guru99Modifiers= constructor.getModifiers();
System.Out.printlin ("Constrctor modifier : "+Modifier.toString(guru99Modifiers));
// Get and print parameter types
Class[] guru99ParamList=constructor.getParameterTypes();
System.out.print ("Constrctor parameter types :");
for (Class class1 : guru99ParamList) {
System.out.println(class1.getName() +" ");
}
System. out.println();
// Get and print exception thrown by constructors
Class[] guru99ExceptionList=constructor.getFxceptionTypes();
System.out.println("Exception thrown by constructors :");
for (Class class1 : guru99ExceptionList) {
System.out.println(class1.getName() +" ");
}
System.out.println();
System.out.println("*******************************************");
}
}
}
















