Abstract: Java reflection mechanism is in the running state, for any class, can know all the attributes and methods of this class; 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.

This article is from The Reflection of Java Knowledge points and Problems selected by Huawei Cloud community.

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 methods on objects is called the Reflection mechanism of the Java language.

Reflection is the mapping of various components of a Java class to Individual Java objects.

For example: a class has: member variables, methods, constructors, packages and other information, the use of reflection technology can be dissected on a class, the mapping of each component into one object.

(Actually: there is a class in a class to describe these member methods, constructors, and join classes.)

reflection

Q: Call class object. What is the difference between class and forName?

Class<A> classA = A.class;

Class<A> classA = Class.forName("A");
Copy the code

A: The first static initialization cannot be done using.class alone, but forname does

For example, if B is A base class of A, how about the following code?

Suppose there are two classes, parent and child, as follows:

static class Parent { }static class Son extends Parent{}
Copy the code

Q: Can instanceof be compared to the parent class, and will it return true?

        Son son = new Son();        if (son instanceof  Parent) {            System.out.println("a instanof B");        }
Copy the code

A: Can be compared and returns true.

Q: Can getClass be compared with the parent class with ==, and will return true, as follows:

Notice that A is A subclass of B.

        Son son = new Son();        if (son.getClass() == Parent.class){            System.out.println("son class == Parent.class");        }
Copy the code

A: No, compiling will give an error. Has to do with Class< generic > = comparison.

Because getClass returns <? Extends Son>,.class returns class

Q: Can you compare the parent class with getClass and.equals, and return true?

            Son son = new Son();        if (son.getClass().equals(Parent.class)){            System.out.println("son class.equals(Parent.class)");        }
Copy the code

A: It can be compared, but it will return false, that is, not equal!

Q: What kinds of getDeclaredXXX are available?

A: Five:

Note the Annotation

The inner class Classed

Construcotor

Field in the Field,

Method

Q: What methods does getMethods() return, and getDeclaredMethods() return?

A:

GetMethods () returns public methods of this class, parent class, and parent interface

GetDeclaredMethods () returns only all methods of this class

The difference between getXXX and getDeclaredXXX is similar.

Filed, Method, Constructor

  • Method can invoke (Object, args)

  • The Constructor can be newInstance (Object)… To make a construct call.

  • Filed can use GET (object) and set(object) to set the property value.

Q: When reflection gets a Method object, what does that.getModifiers() do?

A: Returns the modifier of the method and is an integer.

Q: What happens to the following code?

package com.huawei.testpublic class A { public A(int i ) { System.out.printf("i=" +i); } public static void main(String[] args) { try { A a = (A)Class.forName("com.huawei.test.A").newInstance(); } catch (ClassNotFoundException e) { System.out.printf("ClassNotFoundException"); } catch (InstantiationException e) { System.out.printf("InstantiationException"); } catch (IllegalAccessException e) { System.out.printf("IllegalAccessException"); }}}Copy the code

A:

Print InstantiationException initialization error.

Since A has no default constructor, it cannot be constructed using newInstance.

Instead, construct by getting the correct constructor.

A a = (A)Class.forName("A").getConstructor(int.class).newInstance(123);
Copy the code

Q: How to improve the efficiency of reflection?

A:

Use a high-performance reflection package, such as ReflectASM

Caches reflected objects to avoid repeated retrieval from bytecode each time. (cache! Cache!)

Method reflection can be set method.setaccessible (true) to turn off the security check.

Instead of using getMethods() and then iterating through the filter, use getMethod(methodName) to getMethods by methodName

Leveraging reflection optimization (JIT) in the hotspot VIRTUAL Machine

References:

Segmentfault.com/q/101000000…

www.cnblogs.com/coding-nigh…

Q: Does a method object retrieved by reflection return a reference to the method object or a copy of the method object?

A: When reflection takes A method object, it makes A copy rather than returning A reference directly, so it’s better to cache the same method that is used frequently rather than looking it up every time.

Q:

After getMethods(), you can traverse the method yourself

And getMethod(methodName), why the performance difference?

A:

When getMethods() returns an array of methods, each method is copied once.

GetMethod (methodName) only returns a copy of that method, and that’s where the performance difference is.

Q:

There is actually a cache inside the JVM when the method is retrieved, but it still makes a copy when it is returned externally.

Is the method’s cache persistent?

A:

It is not persistent and will be reclaimed when memory runs out.

The source code is as follows:

private Class.ReflectionData<T> reflectionData() { SoftReference<Class.ReflectionData<T>> reflectionData = this.reflectionData; int classRedefinedCount = this.classRedefinedCount; Class.ReflectionData rd; return reflectionData ! = null && (rd = (Class.ReflectionData)reflectionData.get()) ! = null && rd.redefinedCount == classRedefinedCount ? rd : this.newReflectionData(reflectionData, classRedefinedCount); }Copy the code

You can see that this is a soft reference.

Soft reference definition:

The memory could be recycled, but also can pass – XX: SoftRefLRUPolicyMSPerMB parameters control the timing of the recovery, as long as the GC will be its recovery, if reflectionData recycled after execution reflection method, That would have to be recreated using the newReflectionData method

Q: Is reflection thread-safe?

A: It is thread-safe. To retrieve reflected data, go through CAS. The CAS concept can be seen in the section multithreading.

Q:

A Ordinary method call

B Reflection method call

C Disables the reflection method call for security check, and the performance difference is as follows:

What is the performance difference between b reflection method calls and C reflection method calls with security checks turned off?

What is the performance difference between normal method calls and reflective method calls that turn off security checks?

A: the security check the performance of the consumption is that SecurityManager. CheckPermission (SecurityConstants. CHECK_MEMBER_ACCESS_PERMISSION); This check requires the runtime to request a RuntimePermission(” accessDeclaredMembers “).

So if security checks are not considered, when invoking a reflection method, you should set Method#setAccessible(true)

The performance difference between the normal method and the reflection method is

  1. The Method# Invoke method wraps and unwraps parameters

  2. Method visibility needs to be checked

  3. Parameters to be checked

  4. Reflection methods are difficult to inline

  5. JIT cannot optimize

Click to follow, the first time to learn about Huawei cloud fresh technology ~