即使有一个类并对它一无所知,但其实它本身就包括了许多信息,Java在需要使用到某个类时才会将类加载,并在JVM中以一个java.lang.Class的实例存在。从Class实例开始,可以获得类的许多信息。
1. Java在真正需要使用一个类时才会加以加载,而不是在程序启动时就加载。所谓真正需要通常指的是要使用指定的类生成对象时(或是用户指定要加载类时:Class.forName()、loadClass());声明并不导致类加载。
2.默认在类第一次被加载时会运行静态区域块
3. Class.forName(String name)(静态方法)实现动态加载类
4.static Class forName(String name,boolean initialize,ClassLoader loader)将initialize设置为false时,在加载类时并不会立即运行静态区块,而会在应用类建立对象时才运行静态区块。
5. Class对象表示所加载的类,取得Class对象之后,就可以取得与类相关联的信息
eg:
package 反射;
import java.lang.reflect.*;
public class SimpleClassViewer {
/**
* @param args
*/
public static void main(String[] arg) {
// TODO Auto-generated method stub
String args[]=new String [1];
args[0]="输入输出.CharArrayReaderWriterDemo";
try{
Class c=Class.forName(args[0]);
//取得包代表对象
Package p=c.getPackage();
System.out.printf("package %s;%n",p.getName());
//取得类型修饰,像class、interface
int m=c.getModifiers();
System.out.print(Modifier.toString(m)+" ");
//if is interface
if(Modifier.isInterface(m)){
System.out.print("interface ");
}
else{
System.out.print("class ");
}
System.out.println(c.getName()+" {");
Field[] fields=c.getDeclaredFields();
for(Field field:fields){
//显示权限修饰
System.out.print("\t"+Modifier.toString(field.getModifiers()));
//显示类型名称
System.out.print(" "+field.getType().getName()+" ");
//显示域成员名称
System.out.println(field.getName()+" ");
}
//取得声明的构造函数代表对象
Constructor[] constructors=c.getDeclaredConstructors();
//显示修饰权限
for(Constructor constructor:constructors){
System.out.print("\t"+Modifier.toString(constructor.getModifiers()));
//显示构造函数名称
System.out.println(" "+constructor.getName()+"();");
}
//取得声明的方法成员代表对象
Method[] methods=c.getDeclaredMethods();
for(Method method:methods){
//显示权限修饰
System.out.print("\t"+Modifier.toString(method.getModifiers()));
//显示放回类型名称
System.out.print(" "+method.getReturnType().getName()+" ");
//显示方法名称
System.out.println(method.getName()+"();");
}
System.out.println("}");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("没有指定类");
}
catch(ClassNotFoundException e){
System.out.println("找不到指定类");
}
}
}
Friday, May 1, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment