This article brings you relevant knowledge about java, which mainly introduces a detailed analysis of the reflection mechanism, including an overview of the reflection mechanism, understanding of class classes, and creating runtime classes. Objects and other contents, let’s take a look at them below. I hope it will be helpful to everyone.
Recommended learning: "java video tutorial"
## 1. Java Overview of reflection mechanism
(1) Reflection (reflection) is the key to being regarded as a dynamic language. The reflection mechanism allows the program to execute You can obtain the internal information of any class with the help of ReflectionAPI, and directly operate the internal properties and methods of any object.
(2) After loading the class, a Class type object is generated in the method area of the heap memory (a class has only one Class object). This object contains the complete Structural 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 vividly call it reflection.
(1) Dynamic language
is a type of language that can change its structure at runtime: for example, new functions, objects, and even codes can be introduced, existing functions can be deleted or other structural changes can be made. In layman's terms, the code can change its structure according to certain conditions at runtime. Main dynamic languages: Objective-C, C#, JavaScript, PHP, Python, Erlang.
(2) Static language
Corresponding to dynamic language, a language whose runtime structure is immutable is a static language. 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 has a certain degree of dynamics, and we can use reflection mechanisms and bytecode operations 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 Java reflection mechanismis running 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
- Obtain generic information at runtime and call member variables and methods of any object at runtime
- Process annotations at runtime to generate dynamic agents
Reflection related Main API2. Understanding the Class classjava.lang.Class: Represents a class
- java.lang.reflect.Method: Represents the method of the class
- java.lang.reflect. Field: Represents the member variables of the class
- java.lang.reflect.Constructor: Represents the constructor of the class … …
After the program passes thejavac.exe
command, one or more bytecodes will be generated File (ending with
.class).
Then we use the
java.execommand to interpret and run a certain bytecode file. Equivalent to loading a certain bytecode file into memory. This process is called class loading. The class loaded into the memory is called a runtime class, and this runtime class serves as an instance of
Class.
In other words, an instance ofClass
corresponds to a runtime class.
Runtime classes loaded into memory will be cached for a certain period of time. Within this time, we can obtain this runtime class in different ways.1.2 Illustration of the class loading process
When the program actively uses a class, if the class has not been loaded into the memory, the system will pass the following three steps: steps to initialize this class.
Loading of classes: Load the bytecode content of theclass
file into memory, and convert these static data into The runtime data structure of the method area, and then generates a
java.lang.Classobject representing this class, which serves as the access entrance (i.e. reference address) to the class data in the method area. All 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 class loader.
类的链接:将Java类的二进制代码合并到JVM的运行状态之中的过程。
● 验证:确保加载的类信息符合JVM规范,例如:以cafe开头,没有安全方面的问题
● 准备:正式为类变量(static
)分配内存并设置类变量默认初始值的阶段,这些内存 都将在方法区中进行分配。
● 解析:虚拟机常量池内的符号引用(常量名)替换为直接引用(地址)的过程。
类的初始化:
● 执行类构造器【clinit
】()方法的过程。类构造器【clinit
】()方法是由编译期自动收集类中 所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信 息的,不是构造该类对象的构造器)。
● 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类 的初始化。
● 虚拟机会保证一个类的()方法在多线程环境中被正确加锁和同步。
public class ClassLoadingTest { public static void main(String[] args) { System.out.println(A.m); } } class A { static { m = 300; } static int m = 100; } //第二步:链接结束后m=0 //第三步:初始化后,m的值由<clinit>()方法执行决定 // 这个A的类构造器<clinit>()方法由类变量的赋值和静态代码块中的语句按照顺序合并产生,类似于 // <clinit>(){ // m = 300; // m = 100; // }</clinit></clinit></clinit>
类的主动引用(一定会发生类的初始化)
- 当虚拟机启动,先初始化
main
方法所在的类new
一个类的对象- 调用类的静态成员(除了final常量)和静态方法
- 使用
java.lang.reflect
包的方法对类进行反射调用- 当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类
类的被动引用(不会发生类的初始化)
- 当访问一个静态域时,只有真正声明这个域的类才会被初始化
- 当通过子类引用父类的静态变量,不会导致子类初始化
- 通过数组定义类引用,不会触发此类的初始化
- 引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类的java.lang.Class对象,作为 方法区中类数据的访问入口。
类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器 中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象。
不同类型的类的加载器:
@Test public void test1(){ //对于自定义类,使用系统类加载器进行加载 ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); System.out.println(classLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2:系统类加载器 //调用系统类加载器的getParent():获取扩展类加载器 ClassLoader classLoader1 = classLoader.getParent(); System.out.println(classLoader1);//sun.misc.Launcher$ExtClassLoader@279f2327:扩展类加载器 //调用扩展类加载器的getParent():无法获取引导类加载器 //引导类加载器主要负责加载java的核心类库,无法加载自定义类的。 ClassLoader classLoader2 = classLoader1.getParent(); System.out.println(classLoader2);//null ClassLoader classLoader3 = String.class.getClassLoader(); System.out.println(classLoader3);//null }
使用系统类加载器读取
Properties
配置文件。
/* Properties:用来读取配置文件。 */ @Test public void test2() throws Exception { Properties pros = new Properties(); //此时的文件默认在当前的module下。 //读取配置文件的方式一:// FileInputStream fis = new FileInputStream("jdbc.properties");// FileInputStream fis = new FileInputStream("src\\jdbc1.properties");// pros.load(fis); //读取配置文件的方式二:使用ClassLoader //配置文件默认识别为:当前module的src下 ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); 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); }}
Class
类在Object
类中定义了以下的方法,此方法将被所有子类继承:
public final Class getClass()
以上的方法返回值的类型是一个
Class
类,此类是Java
反射的源头,实际上所谓反射从程序的运行结果来看也很好理解,即:可以通过对象反射求出类的名称。
对象照镜子后可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口。对于每个类而言,
JRE
都为其保留一个不变的Class
类型的对象。
一个Class
对象包含了特定某个结构(class
/interface
/enum
/annotation
/primitivetype
/void
/[]
)的有关信息。
Class
本身也是一个类
Class
对象只能由系统建立对象
一个加载的类在
JVM
中只会有一个Class
实例
一个Class对象对应的是一个加载到
JVM
中的一个.class
文件
每个类的实例都会记得自己是由哪个
Class
实例所生成
通过
Class
可以完整地得到一个类中的所有被加载的结构
#3. Common methods of Class class## first.
Class
class is the source ofReflection
. For any class you want to dynamically load and run, you can only get the corresponding
Function description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
static Class forName(String name)
| Returns the Class object of the specified class name name | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Object newInstance()
| Call the default constructor and return an instance of the Class object
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
getName()
| Returns the name of the entity (class, interface, array class, basic type or void) represented by this Class object
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Class getSuperClass()
| Returns the Class object # of the parent class of the current Class object |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Get the interface of the current | Class object
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns the class loader of this class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Return the Class |
| Constructor[] getConstructors()||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns an array containing some Constructor objects |
| Field[] getDeclaredFields()||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns Field An array of objects |
##Method getMethod(String name,Class … paramTypes) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Method Object, the formal parameter type of this object is paramType |
<h3>3. 哪些类型可以有Class对象?</h3>
<blockquote><p>(1)class: 外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类<br> (2)interface:接口<br> (3)[]:数组<br> (4)enum:枚举<br> (5)annotation:注解@interface<br> (6)primitive type:基本数据类型<br> (7)void</p></blockquote>
<h2>三、获取Class类实例的四种方法</h2>
<h3>1. 调用运行时类的属性:.class</h3>
<blockquote><p>前提:若已知具体的类,通过类的class属性获取,该方法最为安全可靠, 程序性能最高<br> 示例: <code>Class clazz1 = String.class;
2. 通过运行时类的对象,调用getClass()
3.调用Class的静态方法:forName(String classPath)
4. 使用类的加载器:ClassLoader
5. 代码演示@Testpublic void test1() throws ClassNotFoundException { //方式一:调用运行时类的属性:.class Class clazz1 = Person.class; System.out.println(clazz1);//class com.jiaying.java1.Person //方式二:通过运行时类的对象,调用getClass() Person p1 = new Person(); Class clazz2 = p1.getClass(); System.out.println(clazz2);//class com.jiaying.java1.Person //方式三:调用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 //方式四:使用类的加载器:ClassLoader (了解) 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} Copy after login 四、 创建运行时类的对象1. 引入
2. 语法步骤
String name = “atguigu.java.Person";Class clazz = null;clazz = Class.forName(name); Copy after login
Constructor con = clazz.getConstructor(String.class,Integer.class); Copy after login
Person p2 = (Person) con.newInstance("Peter",20);System.out.println(p2); Copy after login 3. 代码演示@Test public void test1() throws IllegalAccessException, InstantiationException { Class<person> clazz = Person.class; /* newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器。 要想此方法正常的创建运行时类的对象,要求: 1.运行时类必须提供空参的构造器 2.空参的构造器的访问权限得够。通常,设置为public。 在javabean中要求提供一个public的空参构造器。原因: 1.便于通过反射,创建运行时类的对象 2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器 */ Person obj = clazz.newInstance(); System.out.println(obj); }</person> Copy after login 4. 体会反射的动态性//体会反射的动态性 @Test public void test2(){ for(int i = 0;i <h2>五、获取运行时类的完整结构</h2><p>提供具有丰富内容的<code>Person</code>类</p><pre class="brush:php;toolbar:false">//接口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<t> 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<string> implements Comparable<string>,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 + '}'; }}</string></string></t> Copy after login 1. 获取当前运行时类的属性结构
@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(); } }} Copy after login 2. 获取当前运行时类的方法结构
@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 0){ System.out.print("throws "); for(int i = 0;i <h3>3. 获取当前运行时类的构造器结构</h3> Copy after login
/* 获取构造器结构 */ @Test public void test1(){ Class clazz = Person.class; //getConstructors():获取当前运行时类中声明为public的构造器 Constructor[] constructors = clazz.getConstructors(); for(Constructor c : constructors){ System.out.println(c); } System.out.println(); //getDeclaredConstructors():获取当前运行时类中声明的所有的构造器 Constructor[] declaredConstructors = clazz.getDeclaredConstructors(); for(Constructor c : declaredConstructors){ System.out.println(c); } } /* 获取运行时类的父类 */ @Test public void test2(){ Class clazz = Person.class; Class superclass = clazz.getSuperclass(); System.out.println(superclass); } /* 获取运行时类的带泛型的父类 */ @Test public void test3(){ Class clazz = Person.class; Type genericSuperclass = clazz.getGenericSuperclass(); System.out.println(genericSuperclass); } /* 获取运行时类的带泛型的父类的泛型 代码:逻辑性代码 vs 功能性代码 */ @Test public void test4(){ Class clazz = Person.class; Type genericSuperclass = clazz.getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) genericSuperclass; //获取泛型类型 Type[] actualTypeArguments = paramType.getActualTypeArguments();// System.out.println(actualTypeArguments[0].getTypeName()); System.out.println(((Class)actualTypeArguments[0]).getName()); }/* 获取运行时类实现的接口 */ @Test public void test5(){ Class clazz = Person.class; Class[] interfaces = clazz.getInterfaces(); for(Class c : interfaces){ System.out.println(c); } System.out.println(); //获取运行时类的父类实现的接口 Class[] interfaces1 = clazz.getSuperclass().getInterfaces(); for(Class c : interfaces1){ System.out.println(c); } } /* 获取运行时类所在的包 */ @Test public void test6(){ Class clazz = Person.class; Package pack = clazz.getPackage(); System.out.println(pack); } /* 获取运行时类声明的注解 */ @Test public void test7(){ Class clazz = Person.class; Annotation[] annotations = clazz.getAnnotations(); for(Annotation annos : annotations){ System.out.println(annos); } }} Copy after login 六、调用运行时类的指定结构关于setAccessible方法的使用
1. 调用运行时类中指定的属性
在Field中:
代码演示: public class ReflectionTest { @Test public void testField() throws Exception { Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.newInstance(); //获取指定的属性:要求运行时类中属性声明为public //通常不采用此方法 Field id = clazz.getField("id"); /* 设置当前属性的值 set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少 */ id.set(p,1001); /* 获取当前属性的值 get():参数1:获取哪个对象的当前属性值 */ int pId = (int) id.get(p); System.out.println(pId); } /* 如何操作运行时类中的指定的属性 -- 需要掌握 */ @Test public void testField1() throws Exception { Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.newInstance(); //1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性 Field name = clazz.getDeclaredField("name"); //2.保证当前属性是可访问的 name.setAccessible(true); //3.获取、设置指定对象的此属性值 name.set(p,"Tom"); System.out.println(name.get(p)); } Copy after login 2. 调用运行时类中的指定的方法
代码演示: /* 如何操作运行时类中的指定的方法 -- 需要掌握 */ @Test public void testMethod() throws Exception { Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.newInstance(); /* 1.获取指定的某个方法 getDeclaredMethod():参数1 :指明获取的方法的名称 参数2:指明获取的方法的形参列表 */ Method show = clazz.getDeclaredMethod("show", String.class); //2.保证当前方法是可访问的 show.setAccessible(true); /* 3. 调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参 invoke()的返回值即为对应类中调用的方法的返回值。 */ Object returnValue = show.invoke(p,"CHN"); //String nation = p.show("CHN"); System.out.println(returnValue); System.out.println("*************如何调用静态方法*****************"); // private static void showDesc() Method showDesc = clazz.getDeclaredMethod("showDesc"); showDesc.setAccessible(true); //如果调用的运行时类中的方法没有返回值,则此invoke()返回null// Object returnVal = showDesc.invoke(null); Object returnVal = showDesc.invoke(Person.class); System.out.println(returnVal);//null } Copy after login 3. 调用运行时类中的指定的构造器代码演示: /* 如何调用运行时类中的指定的构造器 */ @Test public void testConstructor() throws Exception { Class clazz = Person.class; //private Person(String name) /* 1.获取指定的构造器 getDeclaredConstructor():参数:指明构造器的参数列表 */ Constructor constructor = clazz.getDeclaredConstructor(String.class); //2.保证此构造器是可访问的 constructor.setAccessible(true); //3.调用此构造器创建运行时类的对象 Person per = (Person) constructor.newInstance("Tom"); System.out.println(per); }} Copy after login 推荐学习:《java视频教程》 |
The above is the detailed content of Detailed analysis of java reflection mechanism (summary sharing). For more information, please follow other related articles on the PHP Chinese website!