天天看点

Java反射课程教程

1为什么需要反射?(reflect)

person p = new student();

p在编译时的类型是person,但是在运行时是student。

为了让程序在运行时发现对象和类的真实信息,有两种做法:

1,假设我们知道类的具体信息,可以通过instanceof 运算符进行判断。

2,在编译的时候不知道对象和类的信息,可以通过反射获取。

三种获取class对象的方法。

获取class对象第一种class.forname

获取class对象第二种.class

getname() :以 string 的形式返回此 class 对象所表示的实体(类、接口、数组类、基本类型或 void)名称。

getsimplename() :返回源代码中给出的基础类的简称。

newinstance() :创建此 class 对象所表示的类的一个新实例。

forname(string classname) :返回与带有给定字符串名的类或接口相关联的 class 对象

使用反射获取构造器

//获取构造器

constructor[] cons = s.getclass().getconstructors();

for (constructor constructor : cons) {

system.out.println(constructor);

}

使用反射获取公共方法,注意不包括构造方法,但是包括object中的方法

method[] methods = clazz2.getmethods();

system.out.println(methods.length);

for (method method : methods) {

system.out.println(method.getname());

使用反射获取所有包括私有方法,注意不包括构造方法,但是不包括object中的(继承的)方法

使用反射获取属性,getfields只能获取公共属性

2创建持久层框架

/**

* 通用方法获取对象集合