Java核心技术卷5.7
反射
package reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Scanner;
public class ReflectionT {
public static void main(String[] args){
String name;
if(args.length > 0 ) {
name = args[0];
System.out.println(name);
}
else{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name(e.g.java.util.Date):"); // 输入类名 java.time.LocalDate
name = in.next();
}
try{
Class c1 = Class.forName(name);
Class superc1 = c1.getSuperclass(); // ????????????????????????????????????????待熟悉
String modifiers = Modifier.toString(c1.getModifiers());
if(modifiers.length() > 0 )
System.out.println("modifiers:" + modifiers); //modifier 修饰词 public final and so on
System.out.println("class:" + name);
if(superc1 != null && superc1 != Object.class)
System.out.println("extends" + superc1.getName());
System.out.print("\n{\n");
printConstructor(c1);
System.out.println();
// printConstructor(c1);
// System.out.println();
// printConstructor(c1);
// System.out.println();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.exit(0);
}
//输出类的构造器
public static void printConstructor(Class c1){
Constructor[] constructors = c1.getDeclaredConstructors(); //返回所有的构造器
for(Constructor c : constructors){
String name = c.getName();//返回描述 构造器,方法,域名的字符串
System.out.println(" Constructor ");
String modifiers = Modifier.toString(c.getModifiers()); //c.getModifiers() 返回值为int型
if(modifiers.length() > 0 )
System.out.print(modifiers + ":" + name + "(");
// System.out.print(name + "(");
Class[] paramTypes = c.getParameterTypes(); // 参数类型
for(int j = 0 ; j < paramTypes.length ; j++){
if(j > 0 )
System.out.print(",");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
}
方法,实例域待更新。
public static void printMethod(Class c1){
Method[] methods = c1.getDeclaredMethods();
for(Method m : methods){
Class retType = m.getReturnType(); //在method的类中 返回描述返回类型的Class对象
String name = m.getName();
System.out.println(" method ");
String modifiers = Modifier.toString(m.getModifiers());
if(modifiers.length() > 0 )
System.out.print(modifiers + ":" + retType.getName() + ":" + name + "(");
Class[] paramTypes = m.getParameterTypes();// 返回用于描述参数类型的Class数组对象数组
for(int j = 0 ; j < paramTypes.length ; j++){
if(j > 0)
System.out.print(",");
System.out.print(paramTypes[j].getName());
}
System.out.println(")");
}
}
public static void printFields(Class c1){
Field[] fields = c1.getFields();
for(Field f : fields){
Class type = f.getType();
String name = f.getName();
System.out.println(" field ");
String modifiers = Modifier.toString(f.getModifiers());
if(modifiers.length() > 0 )
System.out.println(modifiers + ":" + type.getName() + ":" + name +";");
}
}