I love programming, code makes me happy, I think God is the most powerful programmer, “Hello World” really opens up a World.


JAVA reflection mechanism, TSK, when you see this word when there is a bad feeling, yes, this thing is not very good to understand, so special open this article, from a practical point of view, with the exact code to explain the “reflection” this thing.


Open the X degree encyclopedia and it says:

The JAVA reflection mechanism allows you to know all the properties and methods of any class in the running state. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke object methods is called the Reflection mechanism of the Java language.

You meng force, feel this is not human words, let me this cute new programmer how happy to play.

###### So, throw away the concepts, throw away the definitions, and start with JAVA’s reflection methods and code.

First, there are four JAVA reflection classes you should know about:

Class, Constructor, Field, Method; Class represents the object of a Class. Constructor represents the Constructor object of a Class. Field represents the member variable of a Class. Method represents the Method object of a Class

You suddenly shake, thinking that this thing can completely construct a class, and you should reward yourself with two more shakes (squints).

Then, follow me step by step and teach you how to use the reflection skill.

Create a new Person class

Then let’s look at a Class method

staticClass<? > forName(String className)
// Returns the Class object associated with the Class or interface with the given string nameCopy the code

If you want to give a String argument to a class, give it a String argument. —— Package + class name

// Class represents the object of the Class
Class clazz = Class.forName("com.company.Person");Copy the code

You’ve caught this class! Let’s have fun with him! Your magic is now in the hands of the Constructor —— and JAVA provides a Constructor to keep you entertained.

// Constructor represents the class's Constructor object
Constructor constructor = clazz.getConstructor(String.class, int.class);Copy the code

Look at this code carefully, instantly feel the beauty of programming. Not only do you get the constructor, but you also associate the class you got above (Clazz), and you also determine the type of the argument. Isn’t it? The following code is very important, highlight! (pat).

 T newInstance()
// Create a new instance of the Class represented by this Class objectCopy the code
Object object = constructor.newInstance("hehe", 11);Copy the code

You pass the values along to the instance object through the constructor. Next, get the method!

Access method

// Method represents the Method object of the class
Method fooMethod = clazz.getMethod("foo".String.class);Copy the code

The method call

fooMethod.invoke(object, "haha");Copy the code

You associate the foo method with the class you get (Clazz), determine the type of the argument, and pay the method object fooMethod. When called, you use the method object fooMethod to “activate” the foo method that belongs to object, and you pay it the parameters to “activate” it.

What about methods without parameters?

Method sayMethod = clazz.getMethod("say");
sayMethod.invoke(null);Copy the code

It’s the same routine.

So the next step is where reflection is the most important, and the most fun, we take the member variables.

Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(object, "Du Xiandong");
System.out.println(field.get(object));Copy the code

Let’s take a look at the results:

Printable results

You think something’s wrong, and you look back at Person.

Note the permissions for name

What about private ownership?

This is a very important mechanism in reflection, which can forcibly obtain private member variables and ignore field access checks, which can do a lot of articles. And that’s because of this method.

field.setAccessible(true);Copy the code

Now, do you know how reflection works? But you are still wondering, besides this forcible access to private member variables, what else can be used?


Let’s take an example to solve this problem. First of all, we know that the client, the server thing, the server is going to process the request from the client, and then return the data, so let’s simulate that and look at reflection. Let’s prepare: create two classes, one interface, and one file

Pay attention to names, suffixes and hierarchies

Write in the interface

public String handleRequest(String string);Copy the code

Then two classes implement the interface.

// Note that the two types of print should be slightly different, otherwise it is difficult to distinguish
    @Override
    public String handleRequest(String string) {
        System.out.println("Received request :" + string);
        return "The results"+string;
    }Copy the code

Go to file and paste the following two lines of code

javarise.com/home=com.company.HomeRequestHandler
javarise.com/mine=com.company.MineRequestHandlerCopy the code

OK, here we go. All set! Let’s start simulating the process. Back to the Main

String[] requesUrlArr = {"javarise.com/home"."javarise.com/mine"};
File configFile = new File("src/MyConfig.properties");
Properties configProperties = new Properties();
FileInputStream fileInputStream = new FileInputStream(configFile);
configProperties.load(fileInputStream);
System.out.println(configProperties);Copy the code

As you can see from the code, I simulated two requests and associated them with the file myconfig.properties. With the two lines in the file, We’ve got the HomeRequestHandler and the MineRequestHandler and we’ve got your questions, we’ve got your questions, we’ve got to move on

     for (String url :
                requesUrlArr) {
            // Get the value from properties by key. The value is the name of the class we want to handle the request
            String className = configProperties.getProperty(url);

            // Reflection generates the corresponding class based on the class name
            Class clazz = Class.forName(className);
            // Generate the corresponding instance according to the class
            RequestHandleInterface requestHandle = (RequestHandleInterface) clazz.newInstance();
            String request = requestHandle.handleRequest(url);
            System.out.println(request);
        }Copy the code

Read the notes with your heart. What do you learn? The ability to reflect, great decoupling, new kinds of requests just add a new request = class to file, and then build that class and implement the interface, how about that, the code is very flexible, great decoupling, don’t you think reflection is a powerful thing? Let’s go back and look at the definition of reflection.

The JAVA reflection mechanism allows you to know all the properties and methods of any class in the running state. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke object methods is called the Reflection mechanism of the Java language.

Do you understand the meaning and function of reflection? Of course, there’s more to reflexes than that, but the road has been opened up, and you just need to keep going.


As programmers, we just want to every day is to me how to knock the code more cow force, more beautiful, and I always thought that the knowledge, insight and experience sharing and learning is an important way of self study, so, knowledge sharing appreciation, always look forward to working with you very much in crossing play idea, exchange experience.

Other personal articles: Details of JAVA constructors and code blocks themselves and their execution StringBuilder provides JAVA ArrayList and LinkedList for StringBuilder development Notes