栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Reflection in Java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Reflection in Java

文章目录

Reflection in Java

reflectioncoding

Reflection in Java reflection

Reflection是 Java API , 用于在运行时检查或修改方法、类和接口的行为。

Reflection所需的类在java.lang.reflect这个包。Reflection为我们提供了某对象属于哪个类,以及该类的哪些方法可以被该对象调用。通过Reflection,我们可以在运行时调用方法(invoke methods),而无需考虑它们private等限制。访问限定符(access specifier)

Reflection is an APIwhich is used to examine or modify the behavior of methods, classes, interfaces at runtime.

The required classes for reflection are provided under java.lang.reflect package.Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.

https://www.geeksforgeeks.org/reflection-in-java/

Reflection 可以用来获取以下信息

类:使用方法getClass(),获取某个对象属于哪个类。构造函数 :使用方法 getConstuctor(),获取对象所属的类的公开构造函数。方法 :使用getMethod()获取对象所属的类的公开方法。

Reflection can be used to get information about –

    Class The getClass() method is used to get the name of the class to which an object belongs.Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.
coding

主要学习

通过field name来创建对象,这需要调用getDeclaredField()方法;

通过设置setAccessible(truee)来避开field的限制,比如private的变量,类外面的函数可以访问。

// creates object of the desired field by providing
// the name of field as argument to the
// getDeclaredField method
Field field = cls.getDeclaredField("s");  // s is private field name

// 通过setAccessible方法来避开field的限制
field.setAccessible(true);

// takes object and the new value to be assigned
// to the field as arguments
field.set(obj, "contents to override field s");

示例代码

// A simple Java program to demonstrate the use of reflection
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;


class Test1
{
	public static void main(String args[]) throws Exception
	{
		// Creating object whose property is to be checked
        // 创建对象
		Test obj = new Test();

		// Creating class object from the object using
		// getclass method
        // 使用getClass方法创建对象
		Class cls = obj.getClass();
		System.out.println("The name of class is " +
							cls.getName());

		// Getting the constructor of the class through the
		// object of the class
        // 使用getConstructor方法来获取构造函数
		Constructor constructor = cls.getConstructor();
		System.out.println("The name of constructor is " +
							constructor.getName());

		System.out.println("The public methods of class are : ");

		// Getting methods of the class through the object
		// of the class by using getMethods
		Method[] methods = cls.getMethods();

		// Printing method names
		for (Method method:methods)
			System.out.println(method.getName());
        
        System.out.println();
	
		// creates object of desired method by providing the
		// method name and parameter class as arguments to
		// the getDeclaredMethod
		Method methodcall1 = cls.getDeclaredMethod("method2",
												int.class);

		// invokes the method at runtime
		methodcall1.invoke(obj, 19);

		// creates object of the desired field by providing
		// the name of field as argument to the
		// getDeclaredField method
		Field field = cls.getDeclaredField("s");  // private field here

		// allows the object to access the field irrespective
		// of the access specifier used with the field
        // 通过setAccessible方法来避开field的限制
		field.setAccessible(true);

		// takes object and the new value to be assigned
		// to the field as arguments
		field.set(obj, "JAVA");

		// Creates object of desired method by providing the
		// method name as argument to the getDeclaredMethod
		Method methodcall2 = cls.getDeclaredMethod("method1");

		// invokes the method at runtime
		methodcall2.invoke(obj);

		// Creates object of the desired method by providing
		// the name of method as argument to the
		// getDeclaredMethod method
		Method methodcall3 = cls.getDeclaredMethod("method3");

		// allows the object to access the method irrespective
		// of the access specifier used with the method
		methodcall3.setAccessible(true);

		// invokes the method at runtime
		methodcall3.invoke(obj);
	}
}


// class whose object is to be created
class Test
{
	// creating a private field 私有成员函数
	private String s;

	// creating a public constructor 构造函数
	public Test() { s = "Reflection in Java"; }

	// Creating a public method with no arguments
	public void method1() {
		System.out.println("The string is " + s);
	}

	// Creating a public method with int as argument
	public void method2(int n) {
		System.out.println("The number is " + n);
	}

	// creating a private method
	private void method3() {
		System.out.println("Private method invoked");
	}
}

测试结果

$ java Test1.java
Note: Test1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The name of class is Test
The name of constructor is Test
The public methods of class are :
method2
method1
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll

The number is 19
The string is JAVA
Private method invoked

summary: In Java, we can use the features of reflection to modify private fields. 今天学习了Java 的reflection。

参考:https://www.geeksforgeeks.org/reflection-in-java/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/719390.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号