/**
* Demo6: 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等
* @throws ClassNotFoundException
*/
public static void Demo6() throws ClassNotFoundException
{
Class<?> class1 = null;
class1 = Class.forName("cn.lee.demo.SuperMan");
//取得父类名称
Class<?> superClass = class1.getSuperclass();
System.out.println("Demo6: SuperMan类的父类名: " + superClass.getName());
System.out.println("===============================================");
Field[] fields = class1.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
System.out.println("类中的成员: " + fields[i]);
}
System.out.println("===============================================");
//取得类方法
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() );
}
}
/**
* Demo7: 通过Java反射机制调用类方法
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InstantiationException
*/
public static void Demo7() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException
{
Class<?> class1 = null;
class1 = Class.forName("cn.lee.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);
}
/**
* Demo8: 通过Java反射机制得到类加载器信息
*
* 在java中有三种类类加载器。[这段资料���上截取]
1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。
2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类