Examples to explain the reflection of Java foundation

  • 2021-07-02 23:58:41
  • OfStack

Pre-preparation

Write a real class phone and implement list interface


public class Phone implements List {
  public double price;
  public String name;
  public Phone() {
  }
  public Phone(double price, String name) {
    this.price = price;
    this.name = name;
  }
  public double getPrice() {
    return price;
  }
  public void gege(String h){
    System.out.println("gege Adj. "+h);
  }
  public void setPrice(double price) {
    this.price = price;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return "Phone{" +
        "price=" + price +
        ", name='" + name + '\'' +
        '}';
  }
  @Override
  public int size() {
    return 0;
  }
  @Override
  public boolean isEmpty() {
    return false;
  }
  @Override
  public boolean contains(Object o) {
    return false;
  }
  @Override
  public Iterator iterator() {
    return null;
  }
  @Override
  public Object[] toArray() {
    return new Object[0];
  }
  @Override
  public boolean add(Object o) {
    return false;
  }
  @Override
  public boolean remove(Object o) {
    return false;
  }
  @Override
  public boolean addAll(Collection c) {
    return false;
  }
  @Override
  public boolean addAll(int index, Collection c) {
    return false;
  }
  @Override
  public void clear() {
  }
  @Override
  public Object get(int index) {
    return null;
  }
  @Override
  public Object set(int index, Object element) {
    return null;
  }
  @Override
  public void add(int index, Object element) {
  }
  @Override
  public Object remove(int index) {
    return null;
  }
  @Override
  public int indexOf(Object o) {
    return 0;
  }
  @Override
  public int lastIndexOf(Object o) {
    return 0;
  }
  @Override
  public ListIterator listIterator() {
    return null;
  }
  @Override
  public ListIterator listIterator(int index) {
    return null;
  }
  @Override
  public List subList(int fromIndex, int toIndex) {
    return null;
  }
  @Override
  public boolean retainAll(Collection c) {
    return false;
  }
  @Override
  public boolean removeAll(Collection c) {
    return false;
  }
  @Override
  public boolean containsAll(Collection c) {
    return false;
  }
  @Override
  public Object[] toArray(Object[] a) {
    return new Object[0];
  }
}

1. Four new objects for reflection


public class Test2 {
  public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // No. 1 1 Species 
    Phone p = new Phone(2999," Millet ");
    System.out.println(p);//Phone{price=2999.0, name=' Millet '}
    // No. 1 2 Species   Need 1 Single space parameter structure 
    Class<Phone> phoneClass = Phone.class;
    Phone phone = phoneClass.newInstance();
    phone.setName(" Huawei ");
    phone.setPrice(3499);
    System.out.println(phone);//Phone{price=3499.0, name=' Huawei '}
    // No. 1 3 Species 
    Class<?> aclass = Class.forName("com.demo.bean.Phone");
    Phone p2 = (Phone) aclass.newInstance();
    p2.setPrice(2999);
    p2.setName(" Meizu ");
    System.out.println(p2);//Phone{price=2999.0, name=' Meizu '}
    // No. 1 4 Species , Need 1 Configuration files phone.properties
    String name = ResourceBundle.getBundle("phone").getString("myphone");
    Class<?> bClass = Class.forName(name);
    Phone p3 = (Phone) bClass.newInstance();
    p3.setPrice(3299);
    p3.setName(" Hammer ");
    System.out.println(p3);//Phone{price=3299.0, name=' Hammer '}
  }
}

Configuration file phone. properties

myphone=com.demo.bean.Phone

2. Reflected fetch class, parent class, and implementation interface


public class Test3 {
  public static void main(String[] args) throws ClassNotFoundException {
    String string = ResourceBundle.getBundle("phone").getString("myphone");
    Class<?> aClass = Class.forName(string);
    // Gets the full path of the class 
    System.out.println(aClass.getName());//com.demo.bean.Phone
    // Gets the simple name of the class 
    System.out.println(aClass.getSimpleName());//Phone
    // Gets the parent class of the class 
    Class<?> superclass = aClass.getSuperclass();
    System.out.println(superclass.getName());//java.lang.Object
    System.out.println(superclass.getSimpleName());//Object
    // Get the interface of the class 
    Class<?>[] interfaces = aClass.getInterfaces();
    for (Class<?> in:interfaces
       ) {
      System.out.println(in.getSimpleName());
    }
  }
}

3. Obtaining empty parameters and parametric structures for reflection


public class Test4 {
  public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException {
    String string = ResourceBundle.getBundle("phone").getString("myphone");
    Class<?> aClass = Class.forName(string);
    // A parameterless constructor is called 
    Phone p1 = (Phone) aClass.newInstance();
    p1.setName(" Huawei ");
    p1.setPrice(2999);//Phone{price=2999.0, name=' Huawei '}
    System.out.println(p1);
    // Obtain the construction method without parameters 
    Constructor<?> constructor = aClass.getConstructor();
    System.out.println(constructor);//public com.demo.bean.Phone()
    // Get all the construction methods 
    Constructor<?>[] constructors = aClass.getConstructors();
    for (Constructor<?> c:constructors
       ) {
      System.out.println(c);
    }
  }
}

4. Method of obtaining reflection


public class Test5 {
  public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,InstantiationException,IllegalAccessException,InvocationTargetException{
    String string = ResourceBundle.getBundle("phone").getString("myphone");
    Class<?> aClass = Class.forName(string);
    // Contains the method of the parent class 
    Method[] methods = aClass.getMethods();
    for (Method m:methods
       ) {
      System.out.println(m);
    }
    // Methods in this class, methods without parent classes 
    Method[] declaredMethods = aClass.getDeclaredMethods();
    for (Method m:declaredMethods
       ) {
      System.out.println(m);
    }
    Method gege = aClass.getMethod("gege",String.class);
    // Get gege Permission modifiers for the method 
    System.out.println(Modifier.toString(gege.getModifiers()));
    // Get gege The return value type of the method 
    System.out.println(gege.getReturnType());
    // Settings gege Parameter values of 
    Object o = aClass.newInstance();
    gege.invoke(o,"aa");
  }
}

5. Get fields for reflection


public class Test6 {
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
    String string = ResourceBundle.getBundle("phone").getString("myphone");
    Class<?> aClass = Class.forName(string);
    // You can only call public  Field , But you can get the fields of the parent class 
    Field[] fields = aClass.getFields();
    for (Field f:fields
       ) {
      System.out.println(f.getName());
    }
    // You can only call public  Field, only the fields in this class can be obtained 
    Field[] declaredFields = aClass.getDeclaredFields();
    for (Field f:declaredFields
       ) {
      System.out.println(f.getName());
    }
    // Get a 1 Data type of field 
    Field name = aClass.getField("name");
    String simpleName = name.getType().getSimpleName();
    System.out.println(simpleName);
    name.setAccessible(true);
    Object o = aClass.newInstance();
    name.set(o," Huawei ");
    System.out.println(name.get(o));
  }
}

Summarize


Related articles: