In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to share with you what the concept of java reflection mechanism is and how to use the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.
1. Overview of Java reflection mechanism 1. Java Reflection
(1) Reflection (reflection) is regarded as the key of dynamic language. The reflection mechanism allows the program to obtain the internal information of any class with the help of ReflectionAPI during execution, and can directly manipulate the internal properties and methods of any object.
(2) after the class is loaded, an object of type Class (a class has only one Class object) is generated in the method area of heap memory, which contains the complete structure information of the class. We can see the structure of the class through this object. This object is like a mirror, through which we can see the structure of the class, so we visually call it reflection.
two。 Dynamic language vs static language
(1) dynamic language
Is a language that can change its structure at run time: for example, new functions, objects, or even code can be introduced, existing functions can be deleted, or other structural changes. The popular point is that code can change its structure according to certain conditions at run time.
Main dynamic languages: Object-C, C #, JavaScript, PHP, Python, Erlang.
(2) static language
Corresponding to dynamic languages, languages with immutable runtime structures are static languages. Such as Java, C, C++. Java is not a dynamic language, but Java can be called a "quasi-dynamic language". That is to say, Java is dynamic to a certain extent, and we can use reflection mechanism and bytecode operation to obtain characteristics similar to dynamic languages. The dynamic nature of Java makes programming more flexible!
(3) Research and application of Java reflection mechanism.
Functions provided by the Java reflection mechanism
Determine the class to which any object belongs at run time
Construct an object of any class at run time
Determine the member variables and methods of any class at run time
Get generic information at run time call member variables and methods of any object at run time
Processing annotations to generate dynamic proxies at run time
Major API related to reflection
Java.lang.Class: represents a class
Java.lang.reflect.Method: a method that represents a class
Java.lang.reflect.Field: a member variable that represents a class
Java.lang.reflect.Constructor: the constructor that represents the class. ...
Second, the understanding of Class class 1. A preliminary understanding of the loading process of class 1.1
After the javac.exe command, the program generates one or more bytecode files (at the end of .class).
Then we use the java.exe command to interpret and run a bytecode file. It is equivalent to loading a bytecode file into memory. This process is called class loading. A class that is loaded into memory is called a runtime class, and this runtime class is used as an instance of Class.
In other words, an instance of Class corresponds to a runtime class.
Runtime classes loaded into memory are cached for a certain amount of time. During this time, we can get this runtime class in different ways.
1.2 diagrams of the loading process of classes
When a program actively uses a class, if the class has not been loaded into memory, the system initializes the class through the following three steps.
Class loading: load the bytecode contents of the class file into memory, convert the static data into the runtime data structure of the method area, and then generate a java.lang.Class object that represents the class as the access entry (that is, the reference address) to the class data in the method area. All the class data that needs to be accessed and used can only be accessed through this Class object. This loading process requires the participation of the classloader.
Links to classes: the process of merging the binaries of the Java class into the running state of JVM.
● verification: make sure that the loaded class information conforms to the JVM specification, for example, starting with cafe, there are no security issues
● preparation: the phase in which memory is formally allocated to class variables (static) and the default initial values of class variables are set, all of which will be allocated in the method area.
● parsing: the process of replacing symbolic references (constant names) with direct references (addresses) in the constant pool of virtual machines.
Initialization of the class:
● executes the process of the class constructor [clinit] () method. The class constructor [clinit] () method is generated by automatically collecting the assignment actions of all class variables in the class at compile time and merging statements in static blocks of code. A class constructor is a constructor that constructs a class message, not a constructor that constructs such objects.
When ● initializes a class, if it finds that its parent class has not been initialized, it needs to trigger the initialization of its parent class first.
The ● virtual machine ensures that the () method of a class is properly locked and synchronized in a multithreaded environment.
Public class ClassLoadingTest {public static void main (String [] args) {System.out.println (A.m);}} class A {static {m = 300;} static int m = 100 } / / second step: after the end of the link, the value of m is determined by () method execution / / the class constructor () method of An is generated by the assignment of class variables and the sequential merging of the statements in the static code block, similar to / / () {/ / m = 300 inception / m = 100 X /} 1.3 to know: when will class initialization occur?
Active reference to the class (class initialization must occur)
When the virtual machine starts, initialize the class where the main method is located
New the object of a class
Call static members of the class (except for the final constant) and static methods
Use the method of the java.lang.reflect package to make a reflection call to the class
Initialize a class. If its parent class is not initialized, its parent class will be initialized first.
Passive reference to the class (class initialization does not occur)
When accessing a static domain, only the class that actually declares the domain will be initialized
When the static variable of the parent class is referenced through the subclass, it does not cause the subclass to initialize
Defining a class reference through an array does not trigger the initialization of this class
Reference constants do not trigger initialization of this class (constants are stored in the constant pool of the calling class during the link phase)
1.4 the function of class loader
The role of class loading: load the bytecode contents of the class file into memory, convert the static data into the run-time data structure of the method area, and then generate a java.lang.Class object representing the class in the heap as the access entry to the class data in the method area.
Class caching: the standard JavaSE class loader can find classes as required, but once a class is loaded into the class loader, it will remain loaded (cached) for a period of time. However, the JVM garbage collection mechanism can recycle these Class objects.
1.5 loaders for different types of classes in JVM
1.6 Code demonstration
Loaders for different types of classes:
@ Test public void test1 () {/ / for custom classes, use the system class loader to load ClassLoader classLoader = ClassLoaderTest.class.getClassLoader (); System.out.println (classLoader); / / sun.misc.Launcher$AppClassLoader@18b4aac2: system class loader / / call system class loader getParent (): get extension class loader ClassLoader classLoader1 = classLoader.getParent (); System.out.println (classLoader1) / / sun.misc.Launcher$ExtClassLoader@279f2327: extension class loader / / call the getParent of the extension class loader (): unable to get the boot class loader / / the boot class loader is mainly responsible for loading the core class library of the java and cannot load the custom class. ClassLoader classLoader2 = classLoader1.getParent (); System.out.println (classLoader2); / / null ClassLoader classLoader3 = String.class.getClassLoader (); System.out.println (classLoader3); / / null}
Use the system class loader to read the Properties configuration file.
/ * Properties: used to read the configuration file. * / @ Test public void test2 () throws Exception {Properties pros = new Properties (); / / the file at this time is under the current module by default. / / the first way to read the configuration file: / / FileInputStream fis = new FileInputStream ("jdbc.properties"); / / FileInputStream fis = new FileInputStream ("src\\ jdbc1.properties"); / / pros.load (fis); / / the second way to read the configuration file: use the ClassLoader / / configuration file to recognize by default: ClassLoader classLoader = ClassLoaderTest.class.getClassLoader () under the src of the current module InputStream is = classLoader.getResourceAsStream ("jdbc1.properties"); pros.load (is); String user = pros.getProperty ("user"); String password = pros.getProperty ("password"); System.out.println ("user =" + user + ", password =" + password);}} 2. What is the Class class?
The Class class defines the following method in the Object class, which is inherited by all subclasses:
Public final Class getClass ()
The type of the return value of the above method is a Class class, which is the source of Java reflection. In fact, the so-called reflection is also easy to understand from the running results of the program, that is, the name of the class can be obtained through object reflection.
The information you can get when an object looks in the mirror: the properties, methods, and constructors of a class, and what interfaces are implemented by a class. For each class, JRE retains an object of type Class that is immutable.
A Class object contains information about a particular structure (class/interface/enum/annotation/primitivetype/void/ []).
Class itself is also a class
Class objects can only be created by the system
A loaded class will have only one Class instance in JVM
A Class object corresponds to a .class file loaded into JVM
The instance of each class will remember which Class instance it was generated by.
All the loaded structures in a class can be obtained completely through Class.
The Class class is the root of Reflection. For any class that you want to load and run dynamically, you have to get the corresponding
3. Function description of common method names of Class class static Class forName (String name) returns the Class object Object newInstance () of the specified class name name to call the default constructor Returns an instance of the Class object getName () returns the entities represented by this Class object (class, interface, array class, Basic type or void) name Class getSuperClass () returns the Class object of the parent class of the current Class object Class [] getInterfaces () gets the interface of the current Class object ClassLoader getClassLoader () returns the class loader Class getSuperclass () returns the ClassConstructor [] getConstructors () that represents the superclass of the entity represented by this Class, returns an array Field [] getDeclaredFields () that contains some Constructor objects, and returns an array Method getMethod (String name) of Field objects. Class... ParamTypes) returns a Method object whose formal parameter type is paramType3. Which types can have Class objects?
(1) class: external class, member (member inner class, static inner class), local inner class, anonymous inner class
(2) interface: API
(3) []: array
(4) enum: enumeration
(5) annotation: note @ interface
(6) primitive type: basic data type
(7) void
3. Four methods of obtaining Class class instance 1. Call the property of the runtime class: .class
Premise: if a specific class is known and obtained through the class attribute of the class, this method is the most secure and reliable, and the program performance is the highest.
Example: Class clazz1 = String.class
two。 Call getClass () through the object of the runtime class
Premise: if you know an instance of a class, call the getClass () method of the instance to get the Class object
Example: Class clazz = "www.atguigu.com" .getClass ()
3. Call the static method of Class: forName (String classPath)
Premise: the full class name of a class is known, and the class can be obtained through the static method forName () of the Class class under the classpath, and a ClassNotFoundException may be thrown
Example: Class clazz = Class.forName ("java.lang.String")
4. Use the class loader: ClassLoader
Example:
ClassLoader cl = this.getClass () .getClassLoader ()
Class clazz4 = cl.loadClass ("full class name of the class")
5. The code demonstrates @ Testpublic void test1 () throws ClassNotFoundException {/ / method 1: call the properties of the runtime class:. Class Class clazz1 = Person.class; System.out.println (clazz1); / / class com.jiaying.java1.Person / / method 2: through the objects of the runtime class, call getClass () Person p1 = new Person (); Class clazz2 = p1.getClass () System.out.println (clazz2); / / class com.jiaying.java1.Person / / method 3: call the static method of Class: forName (String classPath) Class clazz3 = Class.forName ("com.jiaying.java1.Person"); Class clazz5 = Class.forName ("java.lang.String"); System.out.println (clazz3) / / class com.jiaying.java1.Person System.out.println (clazz5); / / class java.lang.String System.out.println (clazz1 = = clazz2); / / true System.out.println (clazz1 = = clazz3); / / true / / Mode 4: use the class loader: ClassLoader (understand) ClassLoader classLoader = ReflectionTest.class.getClassLoader () Class clazz4 = classLoader.loadClass ("com.jiaying.java1.Person"); System.out.println (clazz4); / / class com.jiaying.java1.Person System.out.println (clazz1 = = clazz4); / / true} IV. Create object 1 of the runtime class. Introduce
What can I do with the Class object?
Create an object of the class: call the newInstance () method of the Class object
Request:
Class must have a constructor with no parameters.
The access permissions of the constructor of the class need to be sufficient.
Can't you create an object without a parameter-free constructor?
No! The operation can be instantiated only after the constructor in the class is explicitly invoked during the operation and the parameters are passed in.
The steps are as follows:
Through the getDeclaredConstructor of the Class class (Class... ParameterTypes) gets the constructor of the specified formal parameter type of this class
Pass an array of objects to the constructor's parameters, which contains the parameters needed in the constructor.
Instantiate an object through Constructor.
two。 Grammatical steps
(1) obtain the corresponding Class object based on the full class name
String name = "atguigu.java.Person"; Class clazz = null;clazz = Class.forName (name)
(2) call the constructor of the specified parameter structure to generate an instance of Constructor
Constructor con = clazz.getConstructor (String.class,Integer.class)
(3) create the object of the corresponding class through the instance of Constructor, and initialize the class attribute
Person p2 = (Person) con.newInstance ("Peter", 20); System.out.println (p2); 3. The code demonstrates @ Test public void test1 () throws IllegalAccessException, InstantiationException {Class clazz = Person.class; / * newInstance (): call this method to create an object of the corresponding runtime class. The constructor of the empty parameter of the runtime class is called internally. For this method to create objects of the runtime class normally, it is required that: 1. The runtime class must provide a constructor for empty parameters 2. The constructor of the empty parameter must have sufficient access. Typically, it is set to public. An empty parameter constructor for public is required in javabean. Reason: 1. It is easy to create an object of the runtime class through reflection. When the subclass inherits this runtime class, the default call to super () ensures that the parent class has the constructor * / Person obj = clazz.newInstance (); System.out.println (obj);} 4. Experience the dynamics of reflection / / realize the dynamics of reflection @ Test public void test2 () {for (int I = 0 position I)
< 100;i++){ int num = new Random().nextInt(3);//0,1,2 String classPath = ""; switch(num){ case 0: classPath = "java.util.Date"; break; case 1: classPath = "java.lang.Object"; break; case 2: classPath = "com.atguigu.java.Person"; break; } try { Object obj = getInstance(classPath); System.out.println(obj); } catch (Exception e) { e.printStackTrace(); } } } /* 创建一个指定类的对象。 classPath:指定类的全类名 */ public Object getInstance(String classPath) throws Exception { Class clazz = Class.forName(classPath); return clazz.newInstance(); }}五、获取运行时类的完整结构 提供具有丰富内容的Person类 //接口public interface MyInterface { void info();}//注解@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation { String value() default "hello";}//父类public class Creature implements Serializable { private char gender; public double weight; private void breath(){ System.out.println("生物呼吸"); } public void eat(){ System.out.println("生物吃东西"); }}//Person类@MyAnnotation(value="hi")public class Person extends Creature implements Comparable,MyInterface{ private String name; int age; public int id; public Person(){} @MyAnnotation(value="abc") private Person(String name){ this.name = name; } Person(String name,int age){ this.name = name; this.age = age; } @MyAnnotation private String show(String nation){ System.out.println("我的国籍是:" + nation); return nation; } public String display(String interests,int age) throws NullPointerException,ClassCastException{ return interests + age; } @Override public void info() { System.out.println("我是一个人"); } @Override public int compareTo(String o) { return 0; } private static void showDesc(){ System.out.println("我是一个可爱的人"); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", id=" + id + '}'; }}1. 获取当前运行时类的属性结构方法作用public Field[] getFields()返回此Class对象所表示的类或接口的public的Fieldpublic Field[] getDeclaredFields()返回此Class对象所表示的类或接口的全部Field Field方法中: 方法作用public int getModifiers()以整数形式返回此Field的修饰符public Class getType()得到Field的属性类型public String getName()返回Field的名称 @Test public void test1(){ Class clazz = Person.class; //获取属性结构 //getFields():获取当前运行时类及其父类中声明为public访问权限的属性 Field[] fields = clazz.getFields(); for(Field f : fields){ System.out.println(f); } System.out.println(); //getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性) Field[] declaredFields = clazz.getDeclaredFields(); for(Field f : declaredFields){ System.out.println(f); } } //权限修饰符 数据类型 变量名 @Test public void test2(){ Class clazz = Person.class; Field[] declaredFields = clazz.getDeclaredFields(); for(Field f : declaredFields){ //1.权限修饰符 int modifier = f.getModifiers(); System.out.print(Modifier.toString(modifier) + "\t"); //2.数据类型 Class type = f.getType(); System.out.print(type.getName() + "\t"); //3.变量名 String fName = f.getName(); System.out.print(fName); System.out.println(); } }}2. 获取当前运行时类的方法结构方法作用public Method[] getMethods()返回此Class对象所表示的类或接口的public的方法public Method[] getDeclaredMethods()返回此Class对象所表示的类或接口的全部方法 Method类中: 方法作用public Class getReturnType()取得全部的返回值public Class[] getParameterTypes()取得全部的参数public int getModifiers()取得修饰符public Class[] getExceptionTypes()取得异常信息 @Test public void test1(){ Class clazz = Person.class; //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法 Method[] methods = clazz.getMethods(); for(Method m : methods){ System.out.println(m); } System.out.println(); //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法) Method[] declaredMethods = clazz.getDeclaredMethods(); for(Method m : declaredMethods){ System.out.println(m); } } /* @Xxxx 权限修饰符 返回值类型 方法名(参数类型1 形参名1,...) throws XxxException{} */ @Test public void test2(){ Class clazz = Person.class; Method[] declaredMethods = clazz.getDeclaredMethods(); for(Method m : declaredMethods){ //1.获取方法声明的注解 Annotation[] annos = m.getAnnotations(); for(Annotation a : annos){ System.out.println(a); } //2.权限修饰符 System.out.print(Modifier.toString(m.getModifiers()) + "\t"); //3.返回值类型 System.out.print(m.getReturnType().getName() + "\t"); //4.方法名 System.out.print(m.getName()); System.out.print("("); //5.形参列表 Class[] parameterTypes = m.getParameterTypes(); if(!(parameterTypes == null && parameterTypes.length == 0)){ for(int i = 0;i < parameterTypes.length;i++){ if(i == parameterTypes.length - 1){ System.out.print(parameterTypes[i].getName() + " args_" + i); break; } System.out.print(parameterTypes[i].getName() + " args_" + i + ","); } } System.out.print(")"); //6.抛出的异常 Class[] exceptionTypes = m.getExceptionTypes(); if(exceptionTypes.length >0) {System.out.print ("throws"); for (int I = 0 break I < exceptionTypes.length;i++) {if (I = = exceptionTypes.length-1) {System.out.print (substitutionTypes [I]. GetName ()); break } System.out.print (substitutionTypes [I] .getName () + ",");}} System.out.println ();} 3. Gets the constructor structure method of the current runtime class that functions public Constructor [] getConstructors () to return all the public constructors of the class represented by this Class object. Public Constructor [] getDeclaredConstructors () returns all constructors of the class declaration represented by this Class object.
In the Constructor class:
The method uses the public int getModifiers () to get the modifier public String getName () to get the method name public Class [] getParameterTypes () to get the type of the parameter / * get the constructor structure * / @ Test public void test1 () {Class clazz = Person.class; / / getConstructors (): get the constructor Constructor [] constructors = clazz.getConstructors () declared as public in the current runtime class For (Constructor c: constructors) {System.out.println (c);} System.out.println (); / / getDeclaredConstructors (): get all the constructors declared in the current runtime class Constructor [] declaredConstructors = clazz.getDeclaredConstructors (); for (Constructor c: declaredConstructors) {System.out.println (c) }} / * get the parent class of the runtime class * / @ Test public void test2 () {Class clazz = Person.class; Class superclass = clazz.getSuperclass (); System.out.println (superclass);} / * get the parent class of the runtime class with generics * / @ Test public void test3 () {Class clazz = Person.class Type genericSuperclass = clazz.getGenericSuperclass (); System.out.println (genericSuperclass);} / * get the generic code of the generic parent class of the runtime class: logical code vs functional code * / @ Test public void test4 () {Class clazz = Person.class; Type genericSuperclass = clazz.getGenericSuperclass (); ParameterizedType paramType = (ParameterizedType) genericSuperclass / / get the generic type Type [] actualTypeArguments = paramType.getActualTypeArguments (); / / System.out.println (actualTypeArguments [0] .getTypeName ()); System.out.println (Class) actualTypeArguments [0]). GetName ());} / * get the interface implemented by the runtime class * / @ Test public void test5 () {Class clazz = Person.class Class [] interfaces = clazz.getInterfaces (); for (Class c: interfaces) {System.out.println (c);} System.out.println (); / / get the interface Class [] interfaces1 = clazz.getSuperclass (). GetInterfaces () implemented by the parent class of the runtime class; for (Class c: interfaces1) {System.out.println (c) }} / * get the package where the runtime class resides * / @ Test public void test6 () {Class clazz = Person.class; Package pack = clazz.getPackage (); System.out.println (pack);} / * get the annotation of the runtime class declaration * / @ Test public void test7 () {Class clazz = Person.class Annotation [] annotations = clazz.getAnnotations (); for (Annotation annos: annotations) {System.out.println (annos);} VI. The specified structure of the call runtime class
About the use of setAccessible method
Method and Field, Constructor objects all have a setAccessible () method.
SetAccessible enables and disables the switch that accesses the security check.
A parameter value of true indicates that the reflected object should cancel the Java language access check when in use.
Improve the efficiency of reflection. If reflection must be used in the code, and the code needs to be called frequently, set it to true so that private members who are otherwise inaccessible can also access it. A parameter value of false indicates that the reflected object should be checked for Java language access.
1. Call the properties specified in the runtime class
In the reflection mechanism, the properties in the class can be manipulated directly through the Field class, and the contents of the properties can be set and obtained through the set () and get () methods provided by the Field class.
The method acts as public Field getField (String name) to return the Fieldpublic Field getDeclaredField (String name) of the specified public of the class or interface represented by this Class object and the specified Field of the class or interface represented by this Class object.
In Field:
Method functions public Object get (Object obj) to get the property content of this Field on the specified object obj public void set (Object obj,Object value) to set the property content of this Field on the specified object obj
Code demonstration:
Public class ReflectionTest {@ Test public void testField () throws Exception {Class clazz = Person.class; / / create an object of the runtime class Person p = (Person) clazz.newInstance (); / / get the specified property: requires that the property in the runtime class be declared as public / / this method Field id = clazz.getField ("id") is not usually used / * set the value of the current property set (): parameter 1: indicates which object's property parameter is set. 2: set the value of this property to how many * / id.set (pPhon1001) / * get the value of the current property get (): parameter 1: get the current property value of which object * / int pId = (int) id.get (p); System.out.println (pId) } / * how to manipulate the specified properties in the runtime class-you need to master * / @ Test public void testField1 () throws Exception {Class clazz = Person.class; / / create an object of the runtime class Person p = (Person) clazz.newInstance () / / 1. GetDeclaredField (String fieldName): get the attribute Field name = clazz.getDeclaredField ("name") of the specified variable name in the runtime class; / / 2. Make sure that the current property is accessible name.setAccessible (true); / / 3. Gets and sets the property value of the specified object, name.set (p, "Tom"); System.out.println (name.get (p));} 2. Call the specified method in the runtime class
Through reflection, the method in the class is called, which is done through the Method class. Steps:
Through the getMethod of the Class class (String name,Class... The parameterTypes) method takes a Method object and sets the type of parameters required for this method to operate.
The call is then made using Object invoke (Object obj, Object [] args), passing the parameter information of the obj object to be set to the method.
Object invoke (Object obj, Object... Args)
Description:
Object corresponds to the return value of the original method. If the original method has no return value, null is returned at this time.
If the original method is static, the parameter Object obj can be null.
If the formal parameter list of the original method is empty, Object [] args is null
If the original method is declared as private, the setAccessible (true) method of the method object needs to be explicitly called before the invoke () method is called, and the method of private will be accessible.
Code demonstration:
/ * how to operate the specified method in the runtime class-- you need to master * / @ Test public void testMethod () throws Exception {Class clazz = Person.class; / / create the object of the runtime class Person p = (Person) clazz.newInstance (); / * 1. Get a specified method getDeclaredMethod (): parameter 1: indicates the name of the acquired method parameter 2: indicates the formal parameter list of the acquired method * / Method show = clazz.getDeclaredMethod ("show", String.class); / / 2. Ensure that the current method is accessible show.setAccessible (true); / * 3. Call method invoke (): parameter 1: method caller parameter 2: the return value of the argument invoke () that assigns a value to the method parameter is the return value of the method called in the corresponding class. * / Object returnValue = show.invoke (p, "CHN"); / / String nation = p.show ("CHN"); System.out.println (returnValue); System.out.println ("* how to call static methods *"); / / private static void showDesc () Method showDesc = clazz.getDeclaredMethod ("showDesc") ShowDesc.setAccessible (true); / / if the method in the called runtime class does not return a value, this invoke () returns null// Object returnVal = showDesc.invoke (null); Object returnVal = showDesc.invoke (Person.class); System.out.println (returnVal); / / null} 3. Call the specified constructor in the runtime class
Code demonstration:
/ * how to call the specified constructor in the runtime class * / @ Test public void testConstructor () throws Exception {Class clazz = Person.class; / / private Person (String name) / * 1. Get the specified constructor getDeclaredConstructor (): parameter: indicates the parameter list of the constructor * / Constructor constructor = clazz.getDeclaredConstructor (String.class); / / 2. Make sure that the constructor is accessible constructor.setAccessible (true); / / 3. Call this constructor to create an object of the runtime class Person per = (Person) constructor.newInstance ("Tom"); System.out.println (per);}}
These are all the contents of the article "what is the concept of java reflection mechanism and how to use it?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.