java reflection mechanism details and example code

  • 2020-05-12 02:42:37
  • OfStack

java reflection mechanism:

Test entity class

Human, for example


/**
 * Project: Day12_for_lxy
 * Created: Lulu
 * Date: 2016/8/10
 */
public class Human<T> {
  private String name;
  private int age;
  private float height;

  private static int legs = 2;
  private Map<String, String> jobs;
  private T t;

  public int say() {
    System.out.println("I'm" + name);
    return 0;
  }
  private void sleep(Human human) {
    System.out.println(name + " sleep with " + human.name);
  }
  public List<Integer> getList() {
    return new ArrayList<>();
  }
  public Human() {
  }
  private Human(String name, int age, float height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    if (age > 150 || age < 0) {
      throw new RuntimeException("age > 150 || age < 0");
    }
    this.age = age;
  }
  public float getHeight() {
    return height;
  }
  public void setHeight(float height) {
    this.height = height;
  }
  @Override
  public String toString() {
    return "Human{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", height=" + height +
        '}';
  }
}

Test the capture constructor


/**
 * Project: Day12_for_lxy
 * Created: Lulu
 * Date: 2016/8/10
 */
/*
 Capture construction method 
 */
public class TestConstructor {
  public static void main(String[] args) {
    // Get the corresponding class structure ,  This is used to describe Human The class of this class 
    Class<Human> humanClass = Human.class;
    try {
////       This is assuming you know the structure of the constructor 
//      // Gets the constructor for all explicit parameters ,  The access is public (public)
//      Constructor<Human> constructor1 = humanClass.getConstructor(String.class, Integer.TYPE, Float.TYPE);
//
//      Human h1 = constructor1.newInstance(" Xiao Ming ", 18, 1.85f);
//      System.out.println(h1.toString());
//
//      // A constructor ,  Modifier type 
//      int modifiers = constructor1.getModifiers();
//      if (Modifier.isPublic(modifiers)) {
//        System.out.println(" is public");
//      }

//      //// Gets the constructor for all explicit parameters ,  Get is declarative 
//      Constructor<Human> constructor2 = humanClass.getDeclaredConstructor(String.class, Integer.TYPE, Float.TYPE);
//      // All Settings are accessible 
//      constructor2.setAccessible(true);
//      // This allows you to get all the constructors ,  Including private 
//      Human human2 = constructor2.newInstance("zll", 18, 1.80f);
//      System.out.println(human2.toString());

      // You do not know the class structure of the constructor 
      Constructor<?>[] constructors = humanClass.getDeclaredConstructors();

      for (Constructor<?> c : constructors) {
        c.setAccessible(true);
        System.out.println(c.getName());
        System.out.println("===========================");
        // The list of parameters 
        Class<?>[] types = c.getParameterTypes();
        for (Class<?> type : types) {
          System.out.println(type.getTypeName());
        }

        // Modifier type 
        int modifiers = c.getModifiers();
        if (Modifier.isPublic(modifiers)) {
          System.out.println(" Is an open ");
        }else if (Modifier.isPrivate(modifiers)){
          System.out.println(" Is private ");
        }
      }


    } catch (Exception e) {
      e.printStackTrace();
    }

  }
}

Test fetch field


/**
 * Project: Day12_for_lxy
 * Created: Lulu
 * Date: 2016/8/10
 */

/*
 Retrieve attributes :
 Properties include :(  The property name   type   The modifier   The generic  )
 Properties of the parent class 
 Own properties 
 */
public class TestField {
  public static void main(String[] args) {
    Class<Human> humanClass = Human.class;
    Field[] fields = humanClass.getDeclaredFields();
    for (Field f : fields) {

      // The property name 
      System.out.print("  The name : " + f.getName() + " ");
      System.out.println();
      // type 
      System.out.print(" type  :" + f.getType() + " ");
      System.out.println();
      // The modifier 
      int modifiers = f.getModifiers();
      if (Modifier.isPublic(modifiers)) {
        System.out.println(" public ");
      } else if (Modifier.isPrivate(modifiers)) {
        System.out.println(" private ");
      }
    }
    System.out.println("============================ The generic ==================================");
    try {
      // Get through the class structure jobs attribute 
      Field jobs = humanClass.getDeclaredField("jobs");
      // The generic 
      ParameterizedType type = (ParameterizedType) jobs.getAnnotatedType().getType();
      Type[] types = type.getActualTypeArguments();
           for (Type type1 : types) {
        System.out.println(type1);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("=================== Set the value ,  Get the value ============================");

    try {
      Human<Object> human = new Human<>();
      // The static ,  You want to know who to set the value of the property to 
      Field nameField = humanClass.getDeclaredField("name");
      nameField.setAccessible(true);
      nameField.set(human, " The way the new skill ");
      System.out.println(human.getName());

      // static 
      Field legs = humanClass.getDeclaredField("legs");
      int modifiers = legs.getModifiers();
      legs.setAccessible(true);
      if (Modifier.isStatic(modifiers)) {
        System.out.println(" Is static ");
      }
      legs.set(null, 4);
      System.out.println(legs.get(null));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Test capture method


/**
 * Project: Day12_for_lxy
 * Created: Lulu
 * Date: 2016/8/10
 */
/*
 Access method :
 The method name 
 The modifier 
 Return value type 
 The generic 

 Static and non-static 

 Method call 

 */
public class TestMethod {
  public static void main(String[] args) {

    Class<Human> humanClass = Human.class;
    // The method name 
    Method[] ms = humanClass.getDeclaredMethods();
    for (Method m : ms) {
      m.setAccessible(true);
      System.out.print(" The method name : " + m.getName() + "  " );
      int modifiers = m.getModifiers();

      if (Modifier.isPublic(modifiers)) {
        System.out.println(" public ");
      } else if (Modifier.isPrivate(modifiers)) {
        System.out.println(" private ");
      }
    }
    // In the case of determining method parameters    Method names cannot be exclusive 1 The determination of ,  overloading 
    try {
      // Common type 
      Method sayM = humanClass.getDeclaredMethod("say");
      Class<?> returnType = sayM.getReturnType();
      System.out.println(returnType.toString());
      // The generic 
      Method getListM = humanClass.getDeclaredMethod("getList");
      System.out.println(getListM.getReturnType());

      ParameterizedType type = (ParameterizedType) getListM.getAnnotatedReturnType().getType();
      System.out.println(type);
      Type[] ts = type.getActualTypeArguments();
      for (Type t : ts) {
        System.out.println(t);
      }


    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The test retrieves class information


public static void main(String[] args) {
  printClassInfo(Student.class);
}

public static void printClassInfo(Class c){
    //Java Only in the 1 Of the parent class Object
    System.out.println(c.getName());
    System.out.println(c.getSimpleName());
    System.out.println(c.getSuperclass());

    Class[] interfaces = c.getInterfaces();
    for (Class anInterface : interfaces) {
      System.out.println(anInterface);
    }
    // An external class class has only two access modifiers (public  and  default)
    int modifiers = c.getModifiers();
  }

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: