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

Detailed explanation of Java reflection mechanism

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Detailed explanation of Java reflection mechanism

Java reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic information acquisition and the function of dynamically calling the methods of the object is called the reflection mechanism of Java language.

1. About Class

1. Class is a class, a class that describes the class (that is, the class itself), which encapsulates the Method of the description method, the Filed of the description field, the Constructor of the constructor, and so on.

2. The information that can be obtained after the object looks in the mirror (reflected): the data member name, method and constructor of a class, and which interfaces are implemented by a class.

3. For each class, JRE retains an object of immutable Class type.

A Class object contains information about a particular class.

4. Class objects can only be created by the system

5. A class will have only one Class instance in JVM

Public class Person {

String name

Private int age

Public Person () {

System.out.println ("no parameter constructor")

}

Public Person (String name, int age) {

System.out.println ("parametric constructor")

This.name = name

This.age = age

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

Public int getAge () {

Return age

}

Public void setAge (int age) {

This.age = age

}

@ Override

Public String toString () {

Return "Person {" +

"name='" + name +'\'+

", age=" + age +

'}'

}

}

2. There are three ways to obtain classes by reflection mechanism.

/ * *

* there are three ways to get a class by reflection mechanism

, /

@ Test

Public void testGetClass () throws ClassNotFoundException {

Class clazz = null

/ / 1 is obtained directly from the class name .Class.

Clazz = Person.class

System.out.println ("by class name:" + clazz)

/ / 2 is obtained through the object's getClass () method, which is rarely used (usually Object is passed, and only used when you don't know what type it is)

Object obj = new Person ()

Clazz = obj.getClass ()

System.out.println ("through getClass ():" + clazz)

/ / 3 is obtained through the full class name, which is often used, but a ClassNotFoundException exception may be thrown

Clazz = Class.forName ("com.java.reflection.Person")

System.out.println ("get by full class name:" + clazz)

}

By class name: class com.java.reflection.Person

No-parameter constructor

Through getClass (): class com.java.reflection.Person

Get through the full class name: class com.java.reflection.Person3, create an object using newInstance: the called class must have a constructor without parameters

/ * *

* the newInstance () method of the Class class to create an object of the class.

, /

@ Test

Public void testNewInstance ()

Throws ClassNotFoundException, IllegalAccessException, InstantiationException {

Class clazz = Class.forName ("com.java.reflection.Person")

/ / use the newInstance () method of the Class class to create an object of the class

/ / the parameterless constructor of the actual invoked class (that's why when writing a class, write a parameterless constructor, which is for reflection)

/ / in general, if a class declares a constructor with parameters, it also declares a constructor without parameters

Object obj = clazz.newInstance ()

System.out.println (obj)

}

No-parameter constructor

Person {name='null', age=0} 4, ClassLoader class loader

/ * *

* ClassLoader class loader

, /

@ Test

Public void testClassLoader1 () throws ClassNotFoundException, IOException {

/ / 1. Get a class loader for a system

ClassLoader classLoader = ClassLoader.getSystemClassLoader ()

System.out.println ("classloader of the system->" + classLoader)

/ / 2. Get the parent class loader of the system class loader (extended class loader (extensions classLoader))

ClassLoader = classLoader.getParent ()

System.out.println ("extended class loader-- >" + classLoader)

/ / 3. Get the parent class loader of the extended class loader

/ / output to Null, which cannot be directly referenced by Java programs

ClassLoader = classLoader.getParent ()

System.out.println ("launch classloader-- >" + classLoader)

/ /

/ / 4. Test which class loader loads the current class, and the result is the system's class loader.

ClassLoader = Class.forName ("com.java.reflection.Person") .getClassLoader

System.out.println ("which classloader loads the current class-- >" + classLoader)

/ / 5. Test which class loader is responsible for loading the Object class provided by JDK

ClassLoader = Class.forName ("java.lang.Object") .getClassLoader

System.out.println ("which classloader loads the Object classes provided by JDK-- >" + classLoader)

}

Class loader of the system-- > sun.misc.Launcher$AppClassLoader@43be2d65

Extended class loader-- > sun.misc.Launcher$ExtClassLoader@7a9664a1

Start the classloader-- > null

Which class loader loads the current class-- > sun.misc.Launcher$AppClassLoader@43be2d65

Which class loader loads the Object class provided by JDK-- > null

4.1.The getResourceAsStream method

@ Test

Public void testGetResourceAsStream () throws ClassNotFoundException, IOException {

/ / if you write this, the file needs to be placed in the src directory

/ / InputStream in = new FileInputStream ("test.properties")

/ / 5. A main method about class loader

/ / call getResourceAsStream to get the input stream corresponding to the file under the classpath

InputStream in = this.getClass () .getClassLoader ()

.getResourceAsStream ("com/java/reflection/test.properties")

System.out.println ("in:" + in)

Properties properties = new Properties ()

Properties.load (in)

String driverClass = properties.getProperty ("dirver")

String jdbcUrl = properties.getProperty ("jdbcUrl")

/ / garbled codes may occur in Chinese, which need to be converted

String user = new String (properties.getProperty ("user") .getBytes ("ISO-8859-1"), "UTF-8")

String password = properties.getProperty ("password")

System.out.println ("diverClass:" + driverClass)

System.out.println ("user:" + user)

}

The test.properties content is as follows:

Dirver=com.mysql.jdbc.Driver

JdbcUrl=jdbc:mysql://192.168.42.108:3306/test

User=123

Password=123

Results:

In: java.io.BufferedInputStream@2aca0115

DiverClass: com.mysql.jdbc.Driver

User: 1235, Method: methods in the corresponding class

Public class Person {

Private String name

Private int age

/ / add a private method

Private void privateMthod () {

}

Public Person () {

System.out.println ("no parameter constructor")

}

Public Person (String name, int age) {

System.out.println ("parametric constructor")

This.name = name

This.age = age

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

/ * *

*

* @ param age uses Integer instead of int

, /

Public void setName (String name, int age) {

System.out.println ("name:" + name)

System.out.println ("age:" + age)

}

Public int getAge () {

Return age

}

Public void setAge (int age) {

This.age = age

}

@ Override

Public String toString () {

Return "Person {" +

"name='" + name +'\'+

", age=" + age +

'}'

}

}

@ Test

Public void testMethod () throws ClassNotFoundException, NoSuchMethodException

IllegalAccessException, InstantiationException, InvocationTargetException {

Class clazz = Class.forName ("com.java.reflection.Person")

/ / 1. Get the methods in the class corresponding to clazz, but you cannot get the private method.

Method [] methods = clazz.getMethods ()

System.out.print ("getMethods:")

For (Method method: methods) {

System.out.print (method.getName () + ",")

}

/ / 2. Get all the methods (and only those declared in front of the class, including the private method)

Method [] methods2 = clazz.getDeclaredMethods ()

System.out.print ("\ ngetDeclaredMethods:")

For (Method method: methods2) {

System.out.print (method.getName () + ",")

}

/ / 3. Get the specified method

Method method = clazz.getDeclaredMethod ("setName", String.class); / / the first parameter is the method name, followed by the parameter in the method.

System.out.println ("\ nmethod:" + method)

Method method2 = clazz.getDeclaredMethod ("setName", String.class, int.class); / / the first parameter is the method name, followed by the parameter in the method

System.out.println ("method2:" + method2)

/ / 4. Execution method!

Object obj = clazz.newInstance ()

Method2.invoke (obj, "changwen", 22)

}

GetMethods: toString, getName, setName, setName, setAge, getAge, wait, equals, hashCode, getClass, notify, notifyAll

GetDeclaredMethods: toString, getName, setName, setName, setAge, getAge, privateMthod

Method: public void com.java.reflection.Person.setName (java.lang.String)

Method2: public void com.java.reflection.Person.setName (java.lang.String,int)

No-parameter constructor

Name: changwen

Age:22

6. Invoke method

Public class PersonInvoke {

Public PersonInvoke () {

}

Private String method2 () {

Return "Person private String method2"

}

}

Public class StudentInvoke extends PersonInvoke {

Private void method1 (Integer age) {

System.out.println ("Student private void method1, age=:" + age)

}

}

Gets the private method defined by the parent class of the current class

/ * *

* get the private methods defined in the parent class of the current class

* call getSuperclass () directly

, /

@ Test

Public void testGetSuperClass () throws Exception {

String className = "com.java.reflection.StudentInvoke"

Class clazz = Class.forName (className)

Class superClazz = clazz.getSuperclass ()

System.out.println (superClazz)

/ / output result: class com.java.reflection.PersonInvoke

}

Another way of writing

/ * *

* @ param className the full class name of a class

The method name of a method of the * @ param methodName class, which may also be private

* @ param args requires the parameters passed in to call this method. The meaning of variable parameter

The return value of * @ return after calling the method

, /

Public Object invoke (String className, String methodName, Object... Args) {

Object obj = null

Try {

Obj = Class.forName (className). NewInstance ()

Return invoke (obj, methodName, args)

} catch (InstantiationException e) {

E.printStackTrace ()

} catch (IllegalAccessException e) {

E.printStackTrace ()

} catch (ClassNotFoundException e) {

E.printStackTrace ()

}

Return invoke (null, methodName, args)

}

/ * *

The object executed by the * @ param obj method

The method name of a method of the * @ param methodName class, which may also be a private method or a private method defined by the method in the parent class

* @ param args requires the parameters passed in to call this method. The meaning of variable parameter

The return value of * @ return after calling the method

, /

Public Object invoke (Object obj, String methodName, Object... Args) {

/ / 1. Get the Method object

Class [] parameterTypes = new Class [args.length]

For (int iTun0; ipublic com.java.reflection.Person (java.lang.String,java.lang.Integer) 9, Notes (Annotation)

Starting with JDK5.0, Java has added support for metadata (MetaData), that is, Annotation.

An Annotation is actually a special tag in the code that can be read at compile, class load, run time, and perform corresponding processing. By using Annotation, programmers can embed some supplementary information in the source file without changing the logic.

Annotation can be used like modifiers, can be used to modify packages, classes, constructors, methods, member variables, parameters, local variable declarations, this information is stored in the Annotation "name=value" pair.

Annotation can be used to set metadata for program elements (classes, methods, member variables, etc.)

Basic Annotation

When using Annotation, add the @ symbol before it and use the Annotation as a modifier. Used to modify the program elements it supports

Three basic Annotation:

-@ Override: restricts the overriding of parent methods. This annotation can only be used for methods.

-@ Deprecated: used to indicate that a program element (class, method, etc.) is out of date

-@ SuppressWarnings: suppresses compiler warnings.

Custom Annotation

Define a new Annotation type using the @ interface keyword

The member variables of Annotation are declared as parameterless methods in the Annotation definition. Its method name and return value define the name and type of the member.

You can specify an initial value for a member variable of Annotation when you define it, and you can use the default keyword to specify the initial value of a member variable.

Annotation that has no member definition is called tag; Annotation that contains member variables is called metadata Annotation.

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

Internet Technology

Wechat

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

12
Report