Using Java Reflection

2024-06-13 15:48
文章标签 using java reflection

本文主要是介绍Using Java Reflection,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文链接: http://www.oracle.com/technetwork/articles/java/javareflection-1536171.html


 

Using Java Reflection

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.

A Simple Example

To see how reflection works, consider this simple example:

   import java.lang.reflect.*;public class DumpMethods {public static void main(String args[]){try {Class c = Class.forName(args[0]);Method m[] = c.getDeclaredMethods();for (int i = 0; i < m.length; i++)System.out.println(m[i].toString());}catch (Throwable e) {System.err.println(e);}}}

For an invocation of:

  java DumpMethods java.util.Stack 

the output is:

  public java.lang.Object java.util.Stack.push(java.lang.Object)public synchronized java.lang.Object java.util.Stack.pop()public synchronizedjava.lang.Object java.util.Stack.peek()public boolean java.util.Stack.empty()public synchronized int java.util.Stack.search(java.lang.Object)

That is, the method names of class java.util.Stack are listed, along with their fully qualified parameter and return types.

This program loads the specified class using class.forName, and then calls getDeclaredMethods to retrieve the list of methods defined in the class. java.lang.reflect.Method is a class representing a single class method.

Setting Up to Use Reflection

The reflection classes, such as Method, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.lang.Class object for the class that you want to manipulate. java.lang.Class is used to represent classes and interfaces in a running Java program.

One way of obtaining a Class object is to say:

   Class c = Class.forName("java.lang.String"); 
to get the Class object for String. Another approach is to use:
   Class c = int.class; 
or
  Class c = Integer.TYPE; 
to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type.

The second step is to call a method such as getDeclaredMethods, to get a list of all the methods declared by the class.

Once this information is in hand, then the third step is to use the reflection API to manipulate the information. For example, the sequence:

   Class c = Class.forName("java.lang.String");    Method m[] = c.getDeclaredMethods();    System.out.println(m[0].toString()); 
will display a textual representation of the first method declared in String.

In the examples below, the three steps are combined to present self contained illustrations of how to tackle specific applications using reflection.

Simulating the instanceof Operator

Once Class information is in hand, often the next step is to ask basic questions about the Class object. For example, the Class.isInstance method can be used to simulate the instanceof operator:

    class A {}public class instance1 {public static void main(String args[]){try {Class cls = Class.forName("A");boolean b1 = cls.isInstance(new Integer(37));System.out.println(b1);boolean b2 = cls.isInstance(new A());System.out.println(b2);}catch (Throwable e) {System.err.println(e);}}}
In this example, a Class object for A is created, and then class instance objects are checked to see whether they are instances of A. Integer(37) is not, but new A() is.

Finding Out About Methods of a Class

One of the most valuable and basic uses of reflection is to find out what methods are defined within a class. To do this the following code can be used:

   import java.lang.reflect.*;public class method1 {private int f1(Object p, int x) throws NullPointerException{if (p == null)throw new NullPointerException();return x;}public static void main(String args[]){try {Class cls = Class.forName("method1");Method methlist[] = cls.getDeclaredMethods();for (int i = 0; i < methlist.length;i++) {  Method m = methlist[i];System.out.println("name = " + m.getName());System.out.println("decl class = " +m.getDeclaringClass());Class pvec[] = m.getParameterTypes();for (int j = 0; j < pvec.length; j++)System.out.println("param #" + j + " " + pvec[j]);Class evec[] = m.getExceptionTypes();for (int j = 0; j < evec.length; j++)System.out.println("exc #" + j + " " + evec[j]);System.out.println("return type = " +m.getReturnType());System.out.println("-----");}}catch (Throwable e) {System.err.println(e);}}}

The program first gets the Class description for method1, and then calls getDeclaredMethods to retrieve a list of Method objects, one for each method defined in the class. These include public, protected, package, and private methods. If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods.

Once a list of the Method objects has been obtained, it's simply a matter of displaying the information on parameter types, exception types, and the return type for each method. Each of these types, whether they are fundamental or class types, is in turn represented by a Class descriptor.

The output of the program is:
  name = f1decl class = class method1param #0 class java.lang.Objectparam #1 intexc #0 class java.lang.NullPointerExceptionreturn type = int-----name = maindecl class = class method1param #0 class [Ljava.lang.String;return type = void-----

Obtaining Information About Constructors

A similar approach is used to find out about the constructors of a class. For example:

 import java.lang.reflect.*;public class constructor1 {public constructor1(){}protected constructor1(int i, double d){}public static void main(String args[]){try {Class cls = Class.forName("constructor1");Constructor ctorlist[]= cls.getDeclaredConstructors();for (int i = 0; i < ctorlist.length; i++) {Constructor ct = ctorlist[i];System.out.println("name = " + ct.getName());System.out.println("decl class = " +ct.getDeclaringClass());Class pvec[] = ct.getParameterTypes();for (int j = 0; j < pvec.length; j++)System.out.println("param #" + j + " " + pvec[j]);Class evec[] = ct.getExceptionTypes();for (int j = 0; j < evec.length; j++)System.out.println("exc #" + j + " " + evec[j]);System.out.println("-----");}}catch (Throwable e) {System.err.println(e);}}}

There is no return-type information retrieved in this example, because constructors don't really have a true return type.

When this program is run, the output is:

   name = constructor1decl class = class constructor1-----name = constructor1decl class = class constructor1param #0 intparam #1 double-----

Finding Out About Class Fields

It's also possible to find out which data fields are defined in a class. To do this, the following code can be used:

   import java.lang.reflect.*;public class field1 {private double d;public static final int i = 37;String s = "testing";public static void main(String args[]){try {Class cls = Class.forName("field1");Field fieldlist[] = cls.getDeclaredFields();for (int i = 0; i < fieldlist.length; i++) {Field fld = fieldlist[i];System.out.println("name= " + fld.getName());System.out.println("decl class = " +fld.getDeclaringClass());System.out.println("type= " + fld.getType());int mod = fld.getModifiers();System.out.println("modifiers = " +Modifier.toString(mod));System.out.println("-----");}}catch (Throwable e) {System.err.println(e);}}}

This example is similar to the previous ones. One new feature is the use of Modifier. This is a reflection class that represents the modifiers found on a field member, for example " private int". The modifiers themselves are represented by an integer, and Modifier.toString is used to return a string representation in the "official" declaration order (such as " static" before " final"). The output of the program is:
  name = ddecl class = class field1type = doublemodifiers = private-----name = idecl class = class field1type = intmodifiers = public static final-----name = sdecl class = class field1type = class java.lang.Stringmodifiers =----- 

As with methods, it's possible to obtain information about just the fields declared in a class ( getDeclaredFields), or to also get information about fields defined in superclasses ( getFields).

Invoking Methods by Name

So far the examples that have been presented all relate to obtaining class information. But it's also possible to use reflection in other ways, for example to invoke a method of a specified name.

To see how this works, consider the following example:

   import java.lang.reflect.*;public class method2 {public int add(int a, int b){return a + b;}public static void main(String args[]){try {Class cls = Class.forName("method2");Class partypes[] = new Class[2];partypes[0] = Integer.TYPE;partypes[1] = Integer.TYPE;Method meth = cls.getMethod("add", partypes);method2 methobj = new method2();Object arglist[] = new Object[2];arglist[0] = new Integer(37);arglist[1] = new Integer(47);Object retobj = meth.invoke(methobj, arglist);Integer retval = (Integer)retobj;System.out.println(retval.intValue());}catch (Throwable e) {System.err.println(e);}}}

Suppose that a program wants to invoke the add method, but doesn't know this until execution time. That is, the name of the method is specified during execution (this might be done by a JavaBeans development environment, for example). The above program shows a way of doing this.

getMethod is used to find a method in the class that has two integer parameter types and that has the appropriate name. Once this method has been found and captured into a Method object, it is invoked upon an object instance of the appropriate type. To invoke a method, a parameter list must be constructed, with the fundamental integer values 37 and 47 wrapped in Integer objects. The return value (84) is also wrapped in an Integer object.

Creating New Objects

There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

   import java.lang.reflect.*;public class constructor2 {public constructor2(){}public constructor2(int a, int b){System.out.println("a = " + a + " b = " + b);}public static void main(String args[]){try {Class cls = Class.forName("constructor2");Class partypes[] = new Class[2];partypes[0] = Integer.TYPE;partypes[1] = Integer.TYPE;Constructor ct = cls.getConstructor(partypes);Object arglist[] = new Object[2];arglist[0] = new Integer(37);arglist[1] = new Integer(47);Object retobj = ct.newInstance(arglist);}catch (Throwable e) {System.err.println(e);}}} 

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

Changing Values of Fields

Another use of reflection is to change the values of data fields in objects. The value of this is again derived from the dynamic nature of reflection, where a field can be looked up by name in an executing program and then have its value changed. This is illustrated by the following example:

   import java.lang.reflect.*;public class field2 {public double d;public static void main(String args[]){try {Class cls = Class.forName("field2");Field fld = cls.getField("d");field2 f2obj = new field2();System.out.println("d = " + f2obj.d);fld.setDouble(f2obj, 12.34);System.out.println("d = " + f2obj.d);}catch (Throwable e) {System.err.println(e);}}} 

In this example, the d field has its value set to 12.34.

Using Arrays

One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object reference.

To see how arrays work, consider the following example:

   import java.lang.reflect.*;public class array1 {public static void main(String args[]){try {Class cls = Class.forName("java.lang.String");Object arr = Array.newInstance(cls, 10);Array.set(arr, 5, "this is a test");String s = (String)Array.get(arr, 5);System.out.println(s);}catch (Throwable e) {System.err.println(e);}}}

This example creates a 10-long array of Strings, and then sets location 5 in the array to a string value. The value is retrieved and displayed.

A more complex manipulation of arrays is illustrated by the following code:

   import java.lang.reflect.*;public class array2 {public static void main(String args[]){int dims[] = new int[]{5, 10, 15};Object arr = Array.newInstance(Integer.TYPE, dims);Object arrobj = Array.get(arr, 3);Class cls = arrobj.getClass().getComponentType();System.out.println(cls);arrobj = Array.get(arrobj, 5);Array.setInt(arrobj, 10, 37);int arrcast[][][] = (int[][][])arr;System.out.println(arrcast[3][5][10]);}}

This example creates a 5 x 10 x 15 array of ints, and then proceeds to set location [3][5][10] in the array to the value 37. Note here that a multi-dimensional array is actually an array of arrays, so that, for example, after the first Array.get, the result in arrobj is a 10 x 15 array. This is peeled back once again to obtain a 15-long array, and the 10th slot in that array is set using Array.setInt.

Note that the type of array that is created is dynamic, and does not have to be known at compile time.

Summary

Java reflection is useful because it supports dynamic retrieval of information about classes and data structures by name, and allows for their manipulation within an executing Java program. This feature is extremely powerful and has no equivalent in other conventional languages such as C, C++, Fortran, or Pascal.

Glen McCluskey has focused on programming languages since 1988. He consults in the areas of Java and C++ performance, testing, and technical documentation.


这篇关于Using Java Reflection的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1057742

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

22.手绘Spring DI运行时序图

1.依赖注入发生的时间 当Spring loC容器完成了 Bean定义资源的定位、载入和解析注册以后,loC容器中已经管理类Bean 定义的相关数据,但是此时loC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况 发生: 、用户第一次调用getBean()方法时,loC容器触发依赖注入。 、当用户在配置文件中将<bean>元素配置了 lazy-init二false属性,即让