Java 反射机制

1. 什么是反射?

反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为。

2. 我们为何需要反射?

反射能够让我们:

  • 在运行时检测对象的类型;
  • 动态构造某个类的对象;
  • 检测类的属性和方法;
  • 任意调用对象的方法;
  • 修改构造函数、方法、属性的可见性;
  • 以及其他。

反射示例:Class.forName()方法可以通过类或接口的名称(一个字符串或完全限定名)来获取对应的Class对象。forName方法会触发类的初始化。

// 使用反射
Class<?> c = Class.forName("classpath.and.classname");
Object dog = c.newInstance();
Method m = c.getDeclaredMethod("bark", new Class<?>[0]);
m.invoke(dog);

Class c = "foo".getClass();
这返回的是String类型的class

enum E { A, B }
Class c = A.getClass();
A是枚举类型E的实例,所以返回的是E的Class

byte[] bytes = new byte[1024];
Class c = bytes.getClass();

(官方解释数组类型的getClass())Since arrays are Objects, it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte.

Set<String> s = new HashSet<String>();
Class c = s.getClass();
这里Set是一个接口,getClass()返回的是HashSet的class

The .class Syntax

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

TYPE Field for Primitive Type Wrappers

Class c = Double.TYPE;

Methods that Return Classes

Class.getSuperclass()
返回指定类的super class
Class c = javax.swing.JButton.class.getSuperclass();
The super class of javax.swing.JButton is javax.swing.AbstractButton.
Class.getClasses()
返回当前类的所有public classes, interfaces, and enums
Class.getDeclaredClasses()
Returns all of the classes interfaces, and enums that are explicitly declared in this class.


Class.getEnclosingClass()
Returns the immediately enclosing class of the class.
Class c = Thread.State.class().getEnclosingClass();
The enclosing class of the enum Thread.State is Thread.
public class MyClass {
    static Object o = new Object() { 
        public void m() {} 
    };
    static Class<c> = o.getClass().getEnclosingClass();
}
The anonymous class defined by o is enclosed by MyClass.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值