JAVA reflection allows you to know all the properties and methods of any class (class file) at runtime. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language. Dynamically retrieving information from a class is called Java reflection. You can think of it as the anatomy of a class. To dissect a bytecode file, you must have a bytecode file object.

How do I get the bytecode file object?

Example: Create a bean package and create a new Person class under the package

package bean;

public class Person {

private int age;

private String name;

public Person(String name,int age) {

super();

this.age = age;

this.name = name;

System.out.println(“Person param run…” +this.name+”:”+this.age);

}

public Person() {

super();

System.out.println(“person run”);

}

public void show(){

System.out.println(name+”… show run…” +age);

}

private void privateMethod(){

System.out.println(” method run “);

}

public void paramMethod(String str,int num){

System.out.println(“paramMethod run…..” +str+”:”+num);

}

public static void staticMethod(){

System.out.println(” static method run……” );

}

}

package Test28;

import bean.Person;

public class ReflectDemo {

public static void main(String[] args) throws ClassNotFoundException {

// TODO Auto-generated method stub

GetClassObject_1();

getClassObject_2();

getClassObject_3();

}

/ * *

* @throws ClassNotFoundException

* Mode three:

* You can retrieve a given class by its string name, which is even more extensive.

* However, this is done using a method in the Class Class called forName.

* This way as long as there is a name, more extensible, more expansibility.

* /

public static void getClassObject_3() throws ClassNotFoundException {

Output result:

class bean.Person

String classNameString=”bean.Person”;

Class<? > class1=Class.forName(classNameString);

System.out.println(class1);

}

/ * *

* Mode 2:

* Any data type has a static property, class, to get its corresponding class object.

* Relatively simple, but still explicit use of static members of the class, not enough to extend.

* /

public static void getClassObject_2() {

Class clazz = Person.class;

Output: true

Class clazz1 = Person.class;

System.out.println(clazz == clazz1);

}

/ * *

* Method 1: obtain bytecode Object method: 1, Object class getClass() method. To do this, you must specify the concrete class and create the object

* /

Output result:

person run

person run

true

public static void GetClassObject_1() {

Person person = new Person();

Class<? extends Person> clazzClass = person.getClass();

Person p1 = new Person();

Class<? extends Person> clazz1 = p1.getClass();

System.out.println(clazz1 == clazzClass);

}

}

Example 2: Reflection calls the constructor of the class

package Test28;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

public class ReflectDemo2 {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

// createNewObject();

createNewObject_2();

}

/ * *

* Instantiate an object with no parameters

* /

public static void createNewObject() throws ClassNotFoundException,

InstantiationException, IllegalAccessException {

// In the early days of new, the bytecode file of the new class is first searched according to the name of the new class and loaded into memory.

// Create the object of the byte file, and then create the corresponding Person object of the byte file.

bean.Person person = new bean.Person();

/ / now:

String name = “bean.Person”;

// Find the file of the name Class, load it into memory, and generate a Class object.

Class<? > clazzClass = Class.forName(name);

// Create an object for this class

Object object = clazzClass.newInstance();

System.out.println(object.toString());

}

/ * *

* @throws Exception

* Instantiate the parameter object

* /

public static void createNewObject_2() throws Exception {

// Instantiate the class with arguments previously

Bean. Person = new bean.Person(” “, 39);

/ *

* When retrieving an object represented in the class corresponding to the specified name,

* What if the object is initialized without an empty parameter construct?

* Since the specified constructor is used to initialize the object,

* So you should get the constructor first. This is done through the bytecode file object.

* This method is: getConstructor(paramterTypes);

* /

String nameString = “bean.Person”;

// Find the name Class file, load it into memory, and generate a Class object.

Class<? > class1 = Class.forName(nameString);

Constructor<? > constructor = class1.getConstructor(String.class,

int.class);

Constructor. NewInstance (” xiaoming “, 32);

}

}

Example 3: Get the fields in the bytecode file.

package Test28;

import java.io.ObjectInputStream.GetField;

import java.lang.reflect.Field;

public class ReflectDemo3 {

public static void main(String[] args) throws ClassNotFoundException, Exception {

// TODO Auto-generated method stub

getFieldDemo();

}

/ * *

* @throws ClassNotFoundException

* @throws Exception

* Gets the fields in the bytecode file.

* /

public static void getFieldDemo() throws ClassNotFoundException, Exception {

Class<? > class1=Class.forName(“bean.Person”);

Field field=null;

field=class1.getField(“age”); // Only public can be obtained

field=class1.getDeclaredField(“age”); // Get this class only, but private.

field.setAccessible(true); // Uncheck access to private fields, violent access.

Object object=class1.newInstance();

field.set(object, 89);

Object o=field.get(object);

System.out.println(o);

}

}

Example 4: Get methods in bytecode files:

package Test28;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class ReflectDemo4 {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

getMethodDemo();

getMethod_2();

getMethodDemo_3();

}

public static void getMethod_2() throws Exception {

Class<? > class1 = Class.forName(“bean.Person”);

Method method = class1.getMethod(“show”, null);

Object object = class1.newInstance();

Constructor constructor = class1.getConstructor(String.class, int.class);

Object obj = constructor. NewInstance (” xiaoming “, 38);

method.invoke(obj, null);

}

/ * *

* @throws ClassNotFoundException

* Gets all public functions in the specified Class

* /

public static void getMethodDemo() throws ClassNotFoundException {

Class clazzClass = Class.forName(“bean.Person”); // Get all public methods

Method[] methods = clazzClass.getMethods(); // Get only all methods in this class, including private.

for (Method method : methods) {

System.out.println(method);

}

}

public static void getMethodDemo_3() throws Exception,

IllegalArgumentException, InvocationTargetException {

Class<? > clazzClass = Class.forName(“bean.Person”);

Method method = clazzClass.getMethod(“paramMethod”, String.class,

int.class);

Object obj = clazzClass.newInstance();

Method.invoke (OBj, “Xiaoqiang “, 89);

}

}

Exercise: Simulate computer operation

package cn.itcast.reflect.test;

public class Mainboard {

public void run() {

System.out.println(“main board run….” );

}

public void usePCI(PCI p) {//PCI p = new SouncCard();

if (p ! = null) {

p.open();

p.close();

}

}

}

package cn.itcast.reflect.test;

public interface PCI {

public void open();

public void close();

}

package cn.itcast.reflect.test;

public class NetCard implements PCI {

@Override

public void open() {

System.out.println(“net open”);

}

@Override

public void close() {

System.out.println(“net close”);

}

}

package cn.itcast.reflect.test;

public class SoundCard implements PCI {

public void open(){

System.out.println(“sound open”);

}

public void close(){

System.out.println(“sound close”);

}

}

package cn.itcast.reflect.test;

import java.io.File;

import java.io.FileInputStream;

import java.util.Properties;

/ *

* Computer running.

* /

public class ReflectTest {

/ * *

* @param args

* @throws Exception

* /

public static void main(String[] args) throws Exception {

Mainboard mb = new Mainboard();

mb.run();

// Each time you add a device, you need to change the code to pass a newly created object

// mb.usePCI(new SoundCard());

// This can be done without modifying the code.

// Instead of new, just get its class file. Internally implement the action of creating an object.

File configFile = new File(“pci.properties”);

Properties prop = new Properties();

FileInputStream fis = new FileInputStream(configFile);

prop.load(fis);

for(int x=0; x<prop.size(); x++){

String pciName = prop.getProperty(“pci”+(x+1));

Class clazz = Class.forName(pciName); // Use Class to load the PCI subclass.

PCI p = (PCI)clazz.newInstance();

mb.usePCI(p);

}

fis.close();

}

}