在开发工具和框架的时候就会用到反射的知识。
首先用类反射就可以解决下面这3个问题:
1、输出一个对象中所有的方法
public static void printMethod(Object obj)
2、给一个名字,创建出一个以这个名字为类名的对象。
public static Object createObject(String className)
3、根据方法名调用方法
分清概念:类对象和类的对象
**类对象:**相当于动物园里动物身上的介绍它的牌子。
**类的对象:**相当于动物园里的具体的动物——狮子。
java有一个类叫做:java.lang.Class类,是Object的子类,这个类的对象叫做类对象。
获得类对象有三种方式:
1、直接类名.class。
Class c=HashMap.class;
2、getClass()方法
Object o=new HashMap();
Class c2=o.getClass();
3、Class.forName()方法
Class c3=Class.forName("java.util.HashMap");
打印结果;
System.out.println(c==c2);//ture
System.out.println(c2==c3);//ture
打印出一个方法中的所有方法对象
java.lang.reflect包中有三个特别重要的类:
分别是:封装属性信息的Field、方法Method、构造方法Construetor.
要打印一个类中的所有方法,就调用Method,
import java.lang.reflect.*;
....要包含上面的那个包才可以用
Method[] ms=c.getMethods();
for(Method m1:ms)
System.out.println(m1.getName());
使用类对象创建类的对象
Class类中有一个方法:newInstance()。
1、获得类对象
2、用newInstance()利用无参构造方法创建对象。
利用反射调用方法
根据类的对象获得类对象,getMethod或getDeclaredMethod获得一个方法,用invoke(…,…),调用。
反射综合程序
package chp16;
import java.lang.reflect.*;
public class Reflet {
public static void main(String[] args) throws Exception {
Object b=createOject("chp16.Student");
methodInvoke(b,"get");
methodInvoke(b,"setScore");
}
//根据类名 创建对象等价于Student s1=new Student();
static Object createOject(String className) throws Exception{
Class c=Class.forName(className);
Object result=c.newInstance();//调无参的构造方法,创建对象
return result;
Constructor con=c.getConstructor(String.class,int.class);
Object result2=con.newInstance("SUN",19);//调无参的构造方法,创建对象
return result2;
}
//打印一个类中所有的公开方法(包括父类的公开方法)
static void printMethod(String className) throws ClassNotFoundException{
Class s=Class.forName(className);
Method[] ms=s.getMethods();
System.out.print("公开方法");
for(Method meth:ms)
System.out.println(meth.getName());
//打印一个类中的所有方法(不包含父类)
Method[] ms1=s.getDeclaredMethods();
System.out.print("类中所有方法方法");
for(Method meth1:ms1)
System.out.println(meth1.getName());
}
//根据方法名调用方法等价于s1.clone s1.setScore
static void methodInvoke(Object o,String methodName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
Class s=o.getClass();
Method meth=s.getDeclaredMethod(methodName,int.class);
Object a=meth.invoke(o,19);//上面这两句对应于调用的methodInvoke(b,"get");
//上下应该分开,不可以都写在同一个函数里
//用反射可以调用私有方法,因为反射是很底层的
Method methPriv=s.getDeclaredMethod(methodName);//这次调用私有的方法
methPriv.setAccessible(true);//对应于methodInvoke(b,"setScore");
methPriv.invoke(o);
}
}
class Student {
int age;
String name;
int score;
public Student() {
System.out.println("Student()");
}
public Student(String name,int age) {
this.age=age;
this.name=name;
System.out.println("Student((String name,int age)");
}
public void get(int age) {
System.out.println(age);
}
private void setScore(){
System.out.println("no Score");
}
}