Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the steps to use Java reflection

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "what are the steps to use Java reflection". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. The concept of reflection

1. Concept

Reflection means that in the running state, for any class, you can know all the properties and methods of this class, and for any object, you can call any of its methods. This ability to dynamically obtain information and dynamically call object methods is called the reflection mechanism of the java language. Reflection is very powerful, with both advantages and disadvantages.

Advantages: high flexibility. Because reflection is a dynamic compilation, that is, it is not created dynamically until run time & the object instance is obtained.

Disadvantages: low execution efficiency.

2. How to get bytecode file objects

2.1 the concept of metadata

Metadata: metadata refers to the data used to describe the class, that is, the code data of class. All class files are loaded into the virtual machine will be built into class objects, class objects describe what a class has, we all know the implementation of the interface, inheritance of abstract classes, member variables, class variables, member methods, class methods, static methods, etc., this class object is metadata.

Class class: represents a class.

Field class: represents the member variable of the class (member variable is also called the property of the class).

Method class: a method that represents a class.

Constructor class: represents the constructor of the class.

Edit search map

2.2 how to get the class object

2.2.1 get from an object, because any object must be associated with a class object

2.2.2 obtain directly from the class object

2.2.3 obtained through the classloader, because the classloader reads the class file and returns the class object

The object to be used for reflection (a randomly defined object, just for demonstration)

Package org.pdool.reflect

/ * *

* @ author coriander

, /

Public class Npc {

/ / static field

Public static int NPC_TYPE_1 = 1

/ / Private member variables

Private int npcType

/ / Common member variables

Public String name

/ / No parameter constructor

Public Npc () {

}

/ / Parametric constructor

Public Npc (int npcType, String name) {

This.npcType = npcType

This.name = name

}

Public int getNpcType () {

Return npcType

}

Public void setNpcType (int npcType) {

This.npcType = npcType

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

/ / static method

Public static void sayHello (String word) {

System.out.println ("hello" + word)

}

}

Three ways to get reflection class

Package org.pdool.reflect

/ * *

* @ author coriander

, /

Public class ClazzTest {

Public static void main (String [] args) {

/ / the first way to get the Class object

Npc npc1 = new Npc (); / / this new produces a Npc object, a Class object.

Class npcClazz1 = npc1.getClass (); / / get the Class object

System.out.println (npcClazz1.getName ())

/ / the second way to get the Class object

Class npcClazz2 = Npc.class

System.out.println (npcClazz1 = = npcClazz2); / / determine whether the Class object obtained by the first method and the second method is the same

/ / the third way to get the Class object

Try {

Class npcClazz3 = Class.forName ("org.pdool.reflect.Npc"); / / Note that this string must be the real path, that is, the classpath with the package name, the package name. Class name

System.out.println (npcClazz3 = = npcClazz2); / / determine whether the three methods obtain the same Class object

} catch (ClassNotFoundException e) {

E.printStackTrace ()

}

}

}

3. How does reflection get metadata and access

1. Access rights

The default behavior of the reflection mechanism is limited by

The access control of Java can be bypassed through setAccessible.

/ / set the object array accessible flag

Static void setAccessible (AccessibleObject [] array, boolean flag)

2. Acquisition method

Edit search map

2.1 access to static methods

Public static void main (String [] args) throws NoSuchMethodException,InvocationTargetException, IllegalAccessException {

Npc npc = new Npc (1, "Phoenix")

Class npcClazz = Npc.class

/ / the first parameter is the method name, and the second parameter is the function parameter class object. Because there is the possibility of overloading, it is distinguished by the parameter type.

Method sayHello = npcClazz.getMethod ("sayHello", String.class)

SayHello.invoke (npc, "world")

}

2.2 access class methods

Npc npc = new Npc (1, "Phoenix")

System.out.println (npc.getName ())

Class npcClazz = Npc.class

/ / the first parameter is the method name, and the second parameter is the function parameter class object. Because there is the possibility of overloading, it is distinguished by the parameter type.

Method sayHello = npcClazz.getMethod ("setName", String.class)

SayHello.invoke (npc, "world")

System.out.println (npc.getName ())

3. Get the field and read the value of the field

Edit search map

Npc npc = new Npc (1, "Phoenix")

Class npcClazz = Npc.class

/ / get the field and set the accessibility

Field field = npcClazz.getField ("name")

Field.setAccessible (true)

System.out.println (field.get (npc))

4. Get the implemented interface

Edit search map

5. Get the constructor and create an instance

Edit search map

Class npcClazz = Npc.class

Constructor declaredConstructor = npcClazz.getDeclaredConstructor (int.class,String.class)

Npc npc = (Npc) declaredConstructor.newInstance (1, "demon god")

System.out.println (npc.getName ())

6. Get the inherited parent class

Class npcClazz = Npc.class

Class superclass = npcClazz.getSuperclass ()

System.out.println (superclass.getName ())

7. Get comments

Class npcClazz = Npc.class

Annotation [] annotations = npcClazz.getAnnotations ()

/ / Runtime comments

For (Annotation annotation: annotations) {

System.out.println (annotation.getClass () .getName ())

}

4. Reflection instance

Getting metadata is not the ultimate goal, our ultimate goal is to call and access the class at run time. Said too much, or give an example, we all know the IOC of Spring, how to achieve it?

Process:

1. Spring reads the path of bean configured in xml at the time the project starts.

2. Then read the class to the classloader through Class.forName

3. Then create all bean instances through reflection and save them to the container. After starting the container,

4. You can get the bean object directly in the project.

Let's roughly implement this process, because the reading of xml is more troublesome, so we directly use property instead. You just have to experience your thoughts.

Package org.pdool.reflect

Import java.io.IOException

Import java.io.InputStream

Import java.lang.annotation.Annotation

Import java.lang.reflect.Constructor

Import java.lang.reflect.Field

Import java.lang.reflect.InvocationTargetException

Import java.lang.reflect.Method

Import java.util.HashMap

Import java.util.Map

Import java.util.Properties

Import java.util.Set

/ * *

* @ author coriander

, /

Public class ClazzTest {

Public static void main (String [] args) {

Try {

Map container = new HashMap ()

/ / 1. Read configuration

InputStream in = ClazzTest.class.getResourceAsStream ("/ beans.properties")

Properties property = new Properties ()

Property.load (in)

/ / 2. Reflection creates an object

Set keySet = property.keySet ()

For (Object key: keySet) {

/ / 2.1 get the full path of the class

String classStr = (String) property.get (key)

/ / 2.2 load class to the virtual machine

Class beanClazz = Class.forName (classStr)

/ / 2.3 get the default constructor

Constructor declaredConstructor = beanClazz.getDeclaredConstructor ()

/ / 2.4 create an instance

Object o = declaredConstructor.newInstance ()

Container.put ((String) key,o)

}

/ / 3. Get an instance

Npc npc = (Npc) container.get ("npc")

System.out.println (npc = = null)

} catch (Exception e) {

E.printStackTrace ()

}

}

}

5. Summary

When using the Java reflection mechanism, the main steps include:

1. Get the Class object of the target type

two。 Get Constructor class object, method class object or Field class object through Class object

3. Through the Constructor class object and the method class object-Field class object, the specific information of the constructor and method-attribute of the class is obtained respectively, and the subsequent operations are carried out.

That's all for "what are the steps to use Java reflection?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report