Java反射机制
什么是反射
解析一个类,找到该类的字节码对象,从而通过字节码对象来产生实例对象的机制。反射被视为动态语言的关键。反射机制允许程序在执行期取得任何类的内部信息,并直接操作任意对象的内部属性及方法。所以反射大大提高了程序的灵活性(例如:动态代理),可以降低代码的耦合性。
反射机制中常用的类
Class—代表类的类
Field—代表属性的类
Method–代表方法的类
Construct—代表构造方法的类
Annotation—代表注解的类
Package—代表包的类
代码实现
public class ClassDemo {
public static void main(String[] args) throws Exception {
//先获取String的字节码对象
Class<String> cstring=String.class;
//获取实例对象
//newInstance()---默认在调用类的无参构造
//String str=clz.newInstance();
//通过字节码对象调用到String类的有参构造
Constructor c=cstring.getConstructor(char[].class);//传入构造方法参数类型的字节码对象
//获取到的有参构造调用newInstance()传入实际参数构造实例对象
String str=(String) c.newInstance
(new char[]{'1','4','a'});
//获取构造方法
Constructor c1=cstring.getConstructor(String.class);
//传参--构建实例对象
String str1=(String) c1.newInstance("abc");
//通过Integer的全路径名获取Integer的实例对象并赋值
//通过Class.forName()获取字节码对象
Class<Integer> cint=(Class<Integer>) Class.forName("java.lang.Integer");
//获取有参构造方法 new Integer(int )
Constructor c2=cint.getConstructor(int.class);
//传参--构建实例对象
Integer in=(Integer) c2.newInstance(123);
System.out.println(in);
}
}