反射机制

来源:互联网 发布:数据库查询重复字段 编辑:程序博客网 时间:2024/06/09 01:44

Java.lang.class<T>

虚拟机为每个类型管理一个Class对象。

获得类对象

Ø  E.getClass()//Object的方法getClass()

Ø  String className=”java.util.Date”; Class c1=Class.forName(className); 如果找不到该类,此处会抛出有一个已检查异常

Ø  Class c1=Double[].class; T.class 是对Class<T>的使用。

Ø  E.getClass().newInstance();

如何加快加载

当程序启动时,包含main的方法的类会被加载.main会加载它所需要的类,这些被加载的类有要加载他们需要的类,所以一个大型程序启动会很慢。

优化:

Ø  确保main方法中没有显示的引用其他的类。

Ø  通过调用Class.forName()手工加载其他的类.

Class 对象的比较

If (e.getClass()==Employ.class)

函数

GetFields() getMethods() getConstructors();返回 包括超类的公有成员。

GetDeclaredFields() getDeclaredMethods()getDeclaredConstructors();

 

反射的作用:

Ø  利用反射分析类的能力

Ø  在运行中查看对象

Ø  实现数组的操作代码

Ø  利用Method对象,这个对象很像C++中的函数指针。

利用反射分析类的能力

Java.lang.reflect 中Field,Method,Constructor类

getName() getModifer()

 

Constructor类中

getDeclaringClass()  getExceptionTypes() getParameterTypes()getReturnType();

 

Modifer

isXXXxX();

在运行中查看对象

Filed.get(obj);

Filed.set(obj,value);

注意:当Filed为private时,需要使用到Java.lang.AccessibleObject。

Filed Method constructor 都继承自Java.lang.AccessibleObject

 

filed.setAccessible(true)//返回全部为对象double->Double

boolean

isAccessible()

Get the value of the accessible flag for this object.

 

 

static void

setAccessible(AccessibleObject[] array, boolean flag)

Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

void

setAccessible(boolean flag)

Set the accessible flag for this object to the indicated boolean value.

 

实现数组的操作代码

使用 Java.lang.reflect.Array类,允许动态的创建数组。

ObjectarrayGrow(Object o){

         Class c= o.class;

         If(c.isArray()){int len = Array.getLength(o)} else{return}

         Class ContentType= c.getConponentType();//Object method

         Int newlenth = lenth*11/10+10;

         Object newArray= Array.newInstance(ComponentType,newLength);

         Return newArray;

}

利用Method对象-函数指针

Method.invoke(obj,parament[]);

如果为静态函数,则obj为null;

 

 

0 0
原创粉丝点击