How does reflection fetch a class in Java

  • 2020-04-01 04:09:41
  • OfStack

Reflection simply means that you can get all the information about a class, mainly methods and properties.

1. Getting methods includes getting the method's name, the method's return type, the method's access modifier, and executing the method through reflection.

2. Get the property including the name, type, access modifier, and value of the property.

These acquisitions all have corresponding apis to provide operations.

The code is as follows:


package poi;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.apache.poi.xwpf.usermodel.XWPFSettings;
public class ReflectMain {
 public static void main(String[] arg) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException, InstantiationException{
 XWPFSettings ct = new XWPFSettings();
 Class c = ct.getClass();
 System.out.println("--------------------- Specifies the member variables of the class -----------------------");
 System.out.println(" The number of member variables of the class obtained by reflection ");
 System.out.println(c.getDeclaredFields().length);
 for (Field fil : c.getDeclaredFields()) {
  System.out.print(fil.getType()+" ");
  System.out.println(fil.getName());
 }
 System.out.println("------------------------ Class constructor -----------------------");
 for (Constructor constructor : c.getDeclaredConstructors()) {
  System.out.print(Modifier.toString(constructor.getModifiers())+" ");
  System.out.println(constructor.getName());
 }
 System.out.println("-------------------------- Members of the method --------------------------");
 for (Method method : c.getDeclaredMethods()) {
  System.out.print(Modifier.toString(method.getModifiers())+" ");
  System.out.print(method.getReturnType()+" ");
  System.out.println(method.getName());
 }
 System.out.println("--------------------------- Class modifier ------------------------");
 int mod = c.getModifiers();
 String modifier = Modifier.toString(mod);
 System.out.println("modifier = " + modifier);
 System.out.println("------------------------ Specifies the fully qualified name of the class --------------------");
 System.out.println(c.getName());
 System.out.println("------------------------ Specifies the parent qualified name of the class --------------------");
 System.out.println(c.getSuperclass().getName());
 }
}

The above content is the article introduces how to reflect in Java to get all the content of a class, hope to help you in the future learning, but also hope to learn together with you heroes, progress.


Related articles: