您的位置:首页 > 编程语言 > Java开发

Java反射机制详解

2015-06-14 13:53 489 查看
一、什么是反射机制

简单的来说,反射机制指的是程序在运行时能够获取自身的信息。在java中,只要给定类的名字,

那么就可以通过反射机制来获得类的所有信息。

二、哪里用到反射机制

有些时候,我们用过一些知识,但是并不知道它的专业术语是什么,在刚刚学jdbc时用过一行代码,

Class.forName("com.mysql.jdbc.Driver.class").newInstance();但是那时候只知道那行代码是生成

驱动对象实例,并不知道它的具体含义。听了反射机制这节课后,才知道,原来这就是反射,现在很多开发

框架都用到反射机制,hibernate、struts都是用反射机制实现的。

三、反射机制的优点与缺点

为什么要用反射机制?直接创建对象不就可以了吗,这就涉及到了动态与静态的概念,

静态编译:在编译时确定类型,绑定对象,即通过。

动态编译:运行时确定类型,绑定对象。动态编译最大限度发挥了java的灵活性,体现了多

态的应用,有以降低类之间的藕合性。

一句话,反射机制的优点就是可以实现动态创建对象和编译,体现出很大的灵活性,特别是在J2EE的开发中

它的灵活性就表现的十分明显。比如,一个大型的软件,不可能一次就把把它设计的很完美,当这个程序编

译后,发布了,当发现需要更新某些功能时,我们不可能要用户把以前的卸载,再重新安装新的版本,假如

这样的话,这个软件肯定是没有多少人用的。采用静态的话,需要把整个程序重新编译一次才可以实现功能

的更新,而采用反射机制的话,它就可以不用卸载,只需要在运行时才动态的创建和编译,就可以实现该功

能。

四、利用反射机制能获得什么信息

一句话,类中有什么信息,它就可以获得什么信息,不过前提是得知道类的名字,要不就没有后文了

首先得根据传入的类的全名来创建Class对象。

Class c=Class.forName("className");注明:className必须为全名,也就是得包含包名,比如,cn.netjava.pojo.UserInfo;

Object obj=c.newInstance();//创建对象的实例

OK,有了对象就什么都好办了,想要什么信息就有什么信息了。

获得构造函数的方法

Constructor getConstructor(Class[] params)//根据指定参数获得public构造器

Constructor[] getConstructors()//获得public的所有构造器

Constructor getDeclaredConstructor(Class[] params)//根据指定参数获得public和非public的构造器

Constructor[] getDeclaredConstructors()//获得public和非public的所有构造器

获得类方法的方法

Method getMethod(String name, Class[] params),根据方法名,参数类型获得方法

Method[] getMethods()//获得所有的public方法

Method getDeclaredMethod(String name, Class[] params)//根据方法名和参数类型,获得public和非public的方法

Method[] getDeclaredMethods()//获得所以的public和非public方法

获得类中属性的方法

Field getField(String name)//根据变量名得到相应的public变量

Field[] getFields()//获得类中所以public的方法

Field getDeclaredField(String name)//根据方法名获得public和非public变量

Field[] getDeclaredFields()//获得类中所有的public和非public方法

常用的就这些,知道这些,其他的都好办……

下面是我的详细实例代码:

package dhp.com.demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class TestMain {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchFieldException, SecurityException, NoSuchMethodException {
// demo1();
System.out.println("===============");
// demo2();
System.out.println("===============");
// demo3();
System.out.println("===============");
// demo4();
System.out.println("===============");
// demo5();
System.out.println("===============");
// demo6();
System.out.println("===============");
// demo7();
System.out.println("===============");
demo8();
}

/**
* 通过java反射机制得到类的包名和类名
*/
public static void demo1() {
Person person = new Person();
System.out.println("demo1 包名 :"
+ person.getClass().getPackage().getName() + ",完整类名:"
+ person.getClass().getName());
/**
* demo1 包名 :dhp.com.demo,完整类名:dhp.com.demo.Person
*/
}

/**
* 验证所有的类都是Class类的实例对象
*/
public static void demo2() {
// 定义两个类型都未知的Class , 设置初值为null, 看看如何给它们赋值成Person类
Class<?> class1 = null;
Class<?> class2 = null;
// 写法1, 可能抛出 ClassNotFoundException [多用这个写法]
try {
class1 = Class.forName("dhp.com.demo.Person");
System.out.println("Demo2:(写法1) 包名: "
+ class1.getPackage().getName() + "," + "完整类名: "
+ class1.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 写法2
class2 = Person.class;
System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName()
+ "," + "完整类名: " + class2.getName());

/**
* Demo2:(写法1) 包名: dhp.com.demo,完整类名: dhp.com.demo.Person Demo2:(写法2)
* 包名: dhp.com.demo,完整类名: dhp.com.demo.Person
*/
}

/**
* 通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在]
*/
public static void demo3() {
Class<?> class1 = null;
try {
class1 = Class.forName("dhp.com.demo.Person");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 由于这里不能带参数,所以你要实例化的这个类Person,一定要有无参构造函数哈~
try {
Person person = (Person) class1.newInstance();
person.setAge(20);
person.setName("denghb");
System.out.println("Demo3: " + person.getName() + " : "
+ person.getAge());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

/**
* Demo3: denghb : 20
*/
}

/**
* 通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象
*
* @throws ClassNotFoundException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void demo4() throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Class<?> class1 = null;
Person person1 = null;
Person person2 = null;
class1 = Class.forName("dhp.com.demo.Person");
// 得到一系列构造函数集合
Constructor<?>[] constructors = class1.getConstructors();
person1 = (Person) constructors[0].newInstance();
person1.setAge(30);
person1.setName("denghb");

person2 = (Person) constructors[1].newInstance(20, "denghb");
System.out.println("Demo4: " + person1.getName() + " : "
+ person1.getAge() + "  ,   " + person2.getName() + " : "
+ person2.getAge());
/**
* Demo4: denghb : 30 , denghb : 20
*/
}

/**
* 通过Java反射机制操作成员变量, set 和 get
*
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchFieldException
*/
public static void demo5() throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
NoSuchFieldException, SecurityException {
Class<?> class1 = null;
class1 = Class.forName("dhp.com.demo.Person");
Object obj = class1.newInstance();
Field personNameField = class1.getDeclaredField("name");
personNameField.setAccessible(true);
personNameField.set(obj, "晶晶");
System.out.println("Demo5: 修改属性之后得到属性变量的值:" + personNameField.get(obj));
/**
* Demo5: 修改属性之后得到属性变量的值:晶晶
*/
}

/**
* 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等
*
* @throws ClassNotFoundException
*/
public static void demo6() throws ClassNotFoundException {
Class<?> class1 = null;
class1 = Class.forName("dhp.com.demo.SuperMan");
// 取得父类名称
Class<?> superClass = class1.getSuperclass();
System.out.println("Demo6:  SuperMan类的父类名: " + superClass.getName());

Field[] fields = class1.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
System.out.println("类中的成员: " + fields[i]);
}

// 取得类方法
Method[] methods = class1.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println("Demo6,取得SuperMan类的方法:");
System.out.println("函数名:" + methods[i].getName());
System.out.println("函数返回类型:" + methods[i].getReturnType());
System.out.println("函数访问修饰符:"
+ Modifier.toString(methods[i].getModifiers()));
System.out.println("函数代码写法: " + methods[i]);
}
System.out.println("======================");
// 取得类实现的接口,因为接口类也属于Class,所以得到接口中的方法也是一样的方法得到哈
Class<?> interfaces[] = class1.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
System.out.println("实现的接口类名: " + interfaces[i].getName());
}
/**
* Demo6:  SuperMan类的父类名: dhp.com.demo.Person
类中的成员: private boolean dhp.com.demo.SuperMan.BlueBriefs
Demo6,取得SuperMan类的方法:
函数名:fly
函数返回类型:void
函数访问修饰符:public
函数代码写法: public void dhp.com.demo.SuperMan.fly()
Demo6,取得SuperMan类的方法:
函数名:walk
函数返回类型:void
函数访问修饰符:public
函数代码写法: public void dhp.com.demo.SuperMan.walk(int)
Demo6,取得SuperMan类的方法:
函数名:isBlueBriefs
函数返回类型:boolean
函数访问修饰符:public
函数代码写法: public boolean dhp.com.demo.SuperMan.isBlueBriefs()
Demo6,取得SuperMan类的方法:
函数名:setBlueBriefs
函数返回类型:void
函数访问修饰符:public
函数代码写法: public void dhp.com.demo.SuperMan.setBlueBriefs(boolean)
======================
实现的接口类名: dhp.com.demo.ActionInterface
*/
}

/**
* 通过Java反射机制调用类方法
*
* @throws ClassNotFoundException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void demo7() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
InstantiationException {
Class<?> class1 = null;
class1 = Class.forName("dhp.com.demo.SuperMan");
System.out.println("Demo7: \n调用无参方法fly():");

Method method = class1.getMethod("fly");
method.invoke(class1.newInstance());

System.out.println("调用有参方法walk(int m):");
method = class1.getMethod("walk", int.class);
method.invoke(class1.newInstance(), 100);
/**
* Demo7:
调用无参方法fly():
超人会飞耶~~
调用有参方法walk(int m):
超人会走耶~~走了100米就走不动了!
*/
}

/**
* 通过Java反射机制得到类加载器信息 在java中有三种类类加载器。
*
* 1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。
*
* 2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类
*
* 3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。
*
* @throws ClassNotFoundException
*/
public static void demo8() throws ClassNotFoundException {
Class<?> class1 = null;
class1 = Class.forName("dhp.com.demo.SuperMan");
String nameString = class1.getClassLoader().getClass().getName();

System.out.println("Demo8: 类加载器类名: " + nameString);
/**
* Demo8: 类加载器类名: sun.misc.Launcher$AppClassLoader
*/
}
}

/**
*
* @author 邓海波
*
*/
class Person {
private int age;
private String name;

public Person() {

}

public Person(int age, String name) {
this.age = age;
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

/**
*
* @author 邓海波
*
*/
class SuperMan extends Person implements ActionInterface {
private boolean BlueBriefs;

public void fly() {
System.out.println("超人会飞耶~~");
}

public boolean isBlueBriefs() {
return BlueBriefs;
}

public void setBlueBriefs(boolean blueBriefs) {
BlueBriefs = blueBriefs;
}

@Override
public void walk(int m) {
System.out.println("超人会走耶~~走了" + m + "米就走不动了!");
}
}

interface ActionInterface {
public void walk(int m);
}


注意:

* getFields()与getDeclaredFields()区别:getFields()只能访问类中声明为公有的字段,私有的字段它无法访问,能访问从其它类继承来的公有方法.getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法

* getMethods()与getDeclaredMethods()区别:getMethods()只能访问类中声明为公有的方法,私有的方法它无法访问,能访问从其它类继承来的公有方法.getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法

* getConstructors()与getDeclaredConstructors()区别:getConstructors()只能访问类中声明为public的构造函数.getDeclaredConstructors()能访问类中所有的构造函数,与public,private,protect无关

参考资料:http://www.cnblogs.com/jqyp/archive/2012/03/29/2423112.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: