Java accesses class properties and calls methods through reflection

preface Reflection can access properties and call methods on any unknown class or object during code execution The idea ...
Get class
Instantiation class
get attribute
change attributes
Call normal method
Call static method
※ call construction method

preface

Reflection can access properties and call methods on any unknown class or object during code execution

The idea of reflection is to establish a reference to the class, and then pass in the object name, access the object properties or call methods. The Java mechanism is to create a unique instance of each loaded class, and then associate the instance with the class

Get class

  • Through the getClass() method of each instance
Integer a = 1; Class cls 1 = a.getClass(); String b = "Hello"; Class cls2 = b.getClass();
  • Through the static attribute xxx.class of the class
Class cls1 = String.class;
  • By full class name
Class cls3 = null; try { cls3 = Class.forName("java.lang.String"); } catch (ClassNotFoundException e) { e.printStackTrace(); }

Instantiation class

Normal instantiation uses new

int[] ints = new int[1];

Instantiate with reflection using Class.newInstance()

String str = String.class.newInstance();
1, Access instance properties through reflection

Since all classes inherit from the Object class, when we don't know a class, we new it into an Object class. We don't need to explore what it is inside. Then we get its class to establish reflection, and then we use the method xxx.getClass() mentioned above

get attribute

Attribute in the field field field, use Class.getField(String name) for a class to obtain its attribute. The following f is the reflection to the Person class attribute name, and then pass in our instance name through the Field.get(String instanceName) method to obtain the name attribute of this instance

import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws Exception{ Object obj = new Person("zhangsan"); Class cls = obj.getClass(); Field f = cls.getField("name"); Object value = f.get(obj); System.out.println(value); // zhangsan } } class Person{ public String name; public Person(String name){ this.name = name; } }

It can be found that during the process of accessing the properties of the instance: the class name of the instance has not been paid attention to all the time

change attributes

After the reflection is established, you only need to use the set method to change the attribute and pass in the instance name and the modified value

For establishing reflection of private attribute: you need to use Class.getDeclaredField(String name) and set Field.setAccessible(true)

import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws Exception{ Person p = new Person("lisi"); System.out.println(p.getName()); // lisi Class cls = p.getClass(); Field f = cls.getDeclaredField("name"); f.setAccessible(true); f.set(p,"wangwu"); System.out.println(p.getName()); // wangwu } } class Person{ private String name; public Person(String name){ this.name = name; } public String getName() { return this.name; } }
2, Invoke the method of the instance through reflection

The attribute is stored in the Field, while the Method is stored in the Method. Use Class.getMethod(String name,Class valueType1,...,Class valueTypeN) to get the reflection of the Method. Multiple parameters need to pass in the attribute of the parameter multiple times

invoke assignment requires type conversion

Call normal method

After getting the reflection, you can use Method.invoke() to pass in the instance and parameters

import java.lang.reflect.Method; public class Main{ public static void main(String[] args) throws Exception { String s = "Hello World!"; // substring parameters are the index values of two int, start and end characters Method f = String.class.getMethod("substring", int.class, int.class); String t = (String) f.invoke(s,3,7); System.out.println(t); // lo W } }

Call static method

Since it is a static method, invoke does not need to pass in parameters, that is, null

import java.lang.reflect.Method; public class ReflectionUseStaticMethod { public static void main(String[] args) throws Exception { Method m = Integer.class.getMethod("parseInt", String.class); Integer n = (Integer) m.invoke(null,"12"); System.out.println(n); // 12 } }

※ call construction method

As mentioned earlier, newinstance () can be used to instantiate, but it can only call the public parameterless constructor of this class. If the constructor has parameters or is not public, it cannot be called directly through Class.newInstance(). Then you need to call its constructor.

newInstance returns an Object object, so it needs to be transformed downward

import java.lang.reflect.Constructor; public class Main { public static void main(String[] args) throws Exception{ Constructor cs = Integer.class.getConstructor(int.class); Integer a = (Integer) cs.newInstance(123); System.out.println(a); // 123 } }
3, Get parent class through reflection

The parent class can be obtained by using the method Class.getSuperclass()

public class ReflectionGetFatherClass { public static void main(String[] args) throws Exception { Class cls = Integer.class; Class father = cls.getSuperclass(); System.out.println(father); // class java.lang.Number } }
4, Get interface through reflection

Use the method Class.getInterfaces() to get the interface array (the interface is also a class)

package LiaoxuefengTest; public class ReflectionGetInterfaces { public static void main(String[] args) throws Exception { Class cls = Integer.class; Class[] ifs = cls.getInterfaces(); for (Class i:ifs){ System.out.println(i); // interface java.lang.Comparable } } }
finish

Welcome to leave a message in the comment area and follow my CSDN @Ho1aAs

8 November 2021, 06:44 | Views: 6155

Add new comment

For adding a comment, please log in
or create account

0 comments