Home>Article>Java> What is reflection in java

What is reflection in java

青灯夜游
青灯夜游 Original
2021-04-13 17:34:10 18314browse

In Java, reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior. The main functions of the Java reflection mechanism: 1. Determine the class to which any object belongs at runtime; 2. Construct an object of any class at runtime; 3. Call the method of any object at runtime, etc.

What is reflection in java

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

What is reflection?

Mainly refers to the ability of a program to access, detect and modify its own state or behavior

Java reflection?

In the Java runtime environment, for any class, can you know what properties and methods this class has? For any object, can any of its methods be called?

The Java reflection mechanism mainly provides the following functions:

* 1. Determine the class to which any object belongs at runtime.

 * 2. Construct an object of any class at runtime.

* 3. Determine the member variables and methods of any class at runtime.

 * 4. Call the method of any object at runtime.

Reflectio

Reflection is a key property of Java being regarded as a dynamic (or quasi-dynamic) language.

This mechanism allows the program to obtain the internal information of any class with a known name through the Reflection APIs at runtime.

Includes all information about its modifiers (such as public, static, etc.), superclass (such as Object), implemented interfaces (such as Serializable), and its fields and methods, and can change the contents of fields at runtime Or call methods.

Dynamic Language

The definition of dynamic language "When a program is running, it is allowed to change the program structure or variable type. This language is called a dynamic language."

From this point of view, Perl, Python, and Ruby are dynamic languages, while C, Java, and C# are not dynamic languages.

Although Java is not a dynamic language under this definition and classification, it does have a very prominent dynamic related mechanism: Reflection. This word means: reflection, image, reflection. When used in Java, it means that we can load, detect, and use classes at runtime that are completely unknown during compilation.

In other words, a Java program can load a class whose name is known only at runtime, learn its complete structure (but not including method definitions), and generate its object entities, or set values for its fields, or Evoke its methods.

The ability of the program to examine itself is called introspection. Reflection and introspection are two terms that are often mentioned together.

Introduction to Java Reflection API

In the JDK, the Java reflection mechanism is mainly implemented by the following classes. These classes (except the first one) are all located in java.lang.

in the reflect package Class class: represents a class and is located under the java.lang package.

Field class: represents the member variables of the class (member variables are also called attributes of the class).

Method class: represents the method of the class.

Constructor class: represents the construction method of the class.

Array class: Provides static methods for dynamically creating arrays and accessing array elements.

Class object

To use reflection, you first need to obtain the Class object corresponding to the class to be operated on.

In Java, no matter how many objects of a certain class are generated, these objects will correspond to the same Class object.

This Class object is generated by the JVM, through which the structure of the entire class can be learned.

Three commonly used ways to obtain Class objects:

1. Use the static method of the Class class. For example:

Class.forName(“java.lang.String”);

2. Use the .class syntax of the class. Such as:

String.class;

3. Use the getClass() method of the object. Such as:

String str = “aa”; Class

Routine 1: Get the method

The routine DumpMethods class demonstrates the basic function of the Reflection API, which reads the command line The class name specified by the parameter, and then prints the method information of this class.

import java.lang.reflect.Method; public class DumpMethods { public static void main(String[] args) throws Exception //在方法后加上这句,异常就消失了 { //获得字符串所标识的类的class对象 Class classType = Class.forName("java.lang.String");//在此处传入字符串指定类名,所以参数获取可以是一个运行期的行为,可以用args[0] //返回class对象所对应的类或接口中,所声明的所有方法的数组(包括私有方法) Method[] methods = classType.getDeclaredMethods(); //遍历输出所有方法声明 for(Method method : methods) { System.out.println(method); } } }

Routine 2: Calling the method through reflection

Call the method through reflection. See the code and comments for details:

import java.lang.reflect.Method; public class InvokeTester { public int add(int param1, int param2) { return param1 + param2; } public String echo(String message) { return "Hello: " + message; } public static void main(String[] args) throws Exception { // 以前的常规执行手段 InvokeTester tester = new InvokeTester(); System.out.println(tester.add(1, 2)); System.out.println(tester.echo("Tom")); System.out.println("---------------------------"); // 通过反射的方式 // 第一步,获取Class对象 // 前面用的方法是:Class.forName()方法获取 // 这里用第二种方法,类名.class Class classType = InvokeTester.class; // 生成新的对象:用newInstance()方法 Object invokeTester = classType.newInstance(); System.out.println(invokeTester instanceof InvokeTester); // 输出true // 通过反射调用方法 // 首先需要获得与该方法对应的Method对象 Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class }); // 第一个参数是方法名,第二个参数是这个方法所需要的参数的Class对象的数组 // 调用目标方法 Object result = addMethod.invoke(invokeTester, new Object[] { 1, 2 }); System.out.println(result); // 此时result是Integer类型 //调用第二个方法 Method echoMethod = classType.getDeclaredMethod("echo", new Class[]{String.class}); Object result2 = echoMethod.invoke(invokeTester, new Object[]{"Tom"}); System.out.println(result2); } }

Generating objects

If you want to generate objects through the constructor method of a class without parameters, we have two ways:

1. Obtain the Class object first, and then directly generate it through the newInstance() method of the Class object:

Class classType = String.class; Object obj = classType.newInstance();

2. Obtain the Class object first, and then obtain the corresponding Constructor object through the object. Then generate

through the newInstance() method of the Constructor object (where Customer is a custom class with a parameterless constructor and a parameterized constructor):

Class classType = Customer.class; // 获得Constructor对象,此处获取第一个无参数的构造方法的 Constructor cons = classType.getConstructor(new Class[] {}); // 通过构造方法来生成一个对象 Object obj = cons.newInstance(new Object[] {});

If you want to generate an object through the parameterized constructor of a class, you can only use the following method:

(Customer is a custom class with a parameterless constructor and a parameterized constructor. Method, pass in strings and integers)

Class classType = Customer.class; Constructor cons2 = classType.getConstructor(new Class[] {String.class, int.class}); Object obj2 = cons2.newInstance(new Object[] {"ZhangSan",20});

可以看出调用构造方法生成对象的方法和调用一般方法的类似,不同的是从Class对象获取Constructor对象时不需要指定名字,而获取Method对象时需要指定名字。

相关视频教程推荐:Java视频教程

The above is the detailed content of What is reflection in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn