Home Java Javagetting Started Detailed introduction to java reflection mechanism

Detailed introduction to java reflection mechanism

Nov 25, 2019 pm 02:48 PM
java reflection mechanism

Detailed introduction to java reflection mechanism

This article is introduced in the Introduction to Java Programming column to introduce the reflection mechanism in Java in detail, hoping to help students who do not understand this mechanism.

java reflection

The mechanism is in the running state. For any class, all properties and methods (including private ones) of this class can be known; for any object , can call any of its methods and properties; this function of dynamically obtaining information and dynamically calling object methods is called Java's reflection mechanism.

Purpose:

Determine the class to which any object belongs at runtime.

Construct an object of any class at runtime.

Judge the member variables and methods of any class at runtime.

Call the method of any object at runtime.

Generate dynamic proxy.

Reflection related classes

Detailed introduction to java reflection mechanism

class class

obtained in Java program Class objects usually have the following three methods:

1. Use the forName(String clazzName) static method of the Class class. This method requires passing in a string parameter, the value of which is the fully qualified name of a class (the complete package name must be added).

2. Call the class attribute of a certain class to obtain the Class object corresponding to the class.

3. Call the getClass() method of an object. This method is a method in the java.lang.Object class.

Field

Field[] allFields = class2.getDeclaredFields();//获取class对象的所有属性
Field[] publicFields = class2.getFields();//获取class对象的public属性
Field ageField = class2.getDeclaredField("age");//获取class指定属性,可以获得私有属性
Field desField = class2.getField("des");//获取class指定的public属性
Copy after login

Method

Method[] methods = class2.getDeclaredMethods();//获取class对象的所有声明方法
Method[] allMethods = class2.getMethods();//获取class对象的所有public方法 包括父类的方法
Method method = class2.getMethod("info", String.class);//返回次Class对象对应类的、带指定形参列表的public方法
Method declaredMethod = class2.getDeclaredMethod("info", String.class);//返回次Class对象对应类的、
带指定形参列表的方法
Copy after login

Constructor

Constructor<?>[] allConstructors = class2.getDeclaredConstructors();//获取class对象的所有声明构造函数
Constructor<?>[] publicConstructors = class2.getConstructors();//获取class对象public构造函数
Constructor<?> constructor = class2.getDeclaredConstructor(String.class);//获取指定声明构造函数
Constructor publicConstructor = class2.getConstructor(String.class);//获取指定声明的public构造函数
Copy after login

Generating instance objects through reflection

1. Use the newInstance() method of the Class object to create an instance of the corresponding class of the Class object. This method requires that the corresponding class of the Class object has a default constructor, and when the newInstance() method is executed, the default constructor is actually used to create an instance of the class.

2. First use the Class object to obtain the specified Constructor object, and then call the newInstance() method of the Constructor object to create an instance of the corresponding class of the Class object. This way you can choose to use a specified constructor to create the instance.

Calling method

1. Obtain the specified method through the getMethods() method or getMethod() method of the Class object and return the Method array or object.

2. Call the Object invoke(Object obj, Object… args) method in the Method object. The first parameter corresponds to the instance object calling the method, and the second parameter corresponds to the parameters of the method.

Example code:

What is reflection?

package am;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.activation.FileDataSource;
/**
 * 反射是什么:
 *    java中的反射:就是在类的加载过程中,发现类的属性和方法构造方法等信息。可以获得类的属性值,可以调用类的方法。
 *    
 * 
 * 反射获得类的对象。
 *
 */
public class Demo01 {
	public static void main(String[] args) throws Exception{
		// 通过反射,获取类的对象。
		Object obj = create("am.Foo");;
		Foo foo = (Foo)obj;
		System.out.println(foo.a);
		double dou = foo.show(12, "hello");
		System.out.println(dou);
		System.out.println("======================================");
		// 获得类的属性
		showField(obj);
		System.out.println("======================================");
		double a = (double)getFieldValue(obj, "b");
		System.out.println(a);
		System.out.println("========================================");
		// 通过反射调用方法。
		Object ob = getMethodValue(obj,"show",new Class[]{int.class,String.class},new Object[]{23,"abc"});
		double douValue = (double)ob;
		System.out.println(douValue);
	}
//通过反射调用方法,哪个对象,什么名称,参数类型,参数值
	public static Object getMethodValue(Object obj,String method,Class[] paramType,Object[] param)
	throws Exception{
		Class cla = obj.getClass();
		Method me = cla.getDeclaredMethod(method, paramType);
		Object o = me.invoke(obj, param);
		return o;
	}
	// 获取类的属性值:
	public static Object getFieldValue(Object obj,String name)throws Exception{
		Class cla = obj.getClass();// 获取字节码对象。
		Field field = cla.getDeclaredField(name);// 通过属性的名称。获取当前属性。
		Object result = field.get(obj);
		return result;
	}
	// 通过反射,可以获得类的属性信息以及方法信息。
	public static void showField(Object obj){
		// java中对属性类。 Field   方法类:Method
		Class cla = obj.getClass();
		System.out.println("获取类名:"+cla.getName());
		System.out.println("======================================");
		// 获取类的属性:
		Field[] fields = cla.getDeclaredFields();// 获取公开的属性。
		for(Field field : fields){
			System.out.println("获取类的属性类型"+field.getType());
			System.out.println("获取类的属性名称:"+field.getName());
		}
		System.out.println("======================================");
		// 获取类的方法。
		Method[] methods = cla.getDeclaredMethods();
		for(Method method : methods){
			System.out.println("获取方法的返回值类型:"+method.getReturnType());
			System.out.println("获取方法名称:"+method.getName());
			System.out.println("获取方法的参数类型。"+Arrays.toString(method.getParameterTypes()));
		}
		System.out.println("=======================================");
		// 获取类的构造方法:
		Constructor[] cons = cla.getDeclaredConstructors();
		for(Constructor con : cons){
			System.out.println("构造方法的名字:"+con.getName());
			System.out.println("构造方法参数类型:"+Arrays.toString(con.getParameterTypes()));
		}	
	}
	// 如何反射类的实例。
	public static Object create(String name) throws Exception{
		// 反射的方法。Class.forName();
		Class cla = Class.forName(name);
		// 如何获得Object类型对象。
		Object obj = cla.newInstance();
		return obj;
	}
}
// 模拟类。
class Foo{
	int a = 10;
	double b = 20;
	public double show(int p,String str){
		System.out.println("调用方法传入的值是:"+str);
		return a+b+p;
	}
	public Foo(){
	}
	public Foo(int a,int b){
	}
}
Copy after login

More related learning video recommendations: java video tutorial

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles