本篇文章采用小例子来说明,因为我始终觉的,案例驱动是最好的,要不然只看理论的话,看了也不懂,不过建议大家在看完文章之后,在回过头去看看理论,会有更好的理解。
下面是java反射的三个例子
Reflection,通过一个类名,打印出构造函数,方法和变量
package senior; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Scanner; public class ReflectionTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String name; if (args.length > 0) name = args[0]; else { System.out.println("Enter class name (e.g. java.util.Date): "); Scanner in = new Scanner(System.in); name = in.nextLine(); } try { Class<?> cl = Class.forName(name); Class<?> superClass = cl.getSuperclass(); String modifiers = Modifier.toString(cl.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print("class " + name); if (superClass != null && superClass != Object.class) System.out.print("extends " + superClass.getName()); System.out.print("\n{\n"); printConstructors(cl);// 打印构造方法 System.out.println(); printMethods(cl);// 打印方法 System.out.println(); printFields(cl);// 打印数据成员 System.out.println("}"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); } private static void printFields(Class<?> cl) { // TODO Auto-generated method stub Field[] fields = cl.getDeclaredFields(); for (Field f : fields) { System.out.print("\t"); Class<?> type = f.getType(); String name = f.getName(); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.println(type.getName() + " " + name + ";"); } } private static void printMethods(Class<?> cl) { // TODO Auto-generated method stub Method[] methods = cl.getDeclaredMethods(); for (Method m : methods) { System.out.print("\t"); Class<?> retType = m.getReturnType(); String name = m.getName(); String modifiers = Modifier.toString(m.getModifiers()); System.out.print(modifiers + " "); System.out.print(retType + " " + name + "("); @SuppressWarnings("rawtypes") Class[] paramTypes = m.getParameterTypes(); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } } private static void printConstructors(Class<?> cl) { // TODO Auto-generated method stub @SuppressWarnings("rawtypes") Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor<?> c : constructors) { System.out.print("\t"); String name = c.getName(); String modifiers = Modifier.toString(c.getModifiers()); System.out.print(modifiers + " "); System.out.print(name + "("); @SuppressWarnings("rawtypes") 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(");"); } } }
运行结果:
MethodPointer相当于C/C++中的回调函数
package senior; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MethodPointerTest { /** * @param args * @throws NoSuchMethodException * @throws SecurityException */ public static void main(String[] args) throws SecurityException, NoSuchMethodException { // TODO Auto-generated method stub Method square = MethodPointerTest.class.getMethod("square", double.class); Method sqrt = Math.class.getMethod("sqrt", double.class); printTable(1, 10, 10, square); printTable(1, 10, 10, sqrt); } public static double square(double x) { return x * x; } private static void printTable(int i, int j, int k, Method f) { // TODO Auto-generated method stub double x = (j - i) / (k - 1); for (double l = i; l <= j; l += x) { double y; try { y = (Double) f.invoke(null, l); System.out.printf("%10.4f|%10.4f%n", l, y); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
运行结果:
泛型反射实例
package junior; import java.lang.reflect.*; import java.util.*; public class GenericReflectionTest { public static void main(String[] args) { // read class name from command line args or user input String name; if (args.length > 0) name = args[0]; else { Scanner in = new Scanner(System.in); System.out .println("Enter class name (e.g. java.util.Collections): "); name = in.next(); } try { // print generic info for class and public methods Class<?> cl = Class.forName(name); printClass(cl); for (Method m : cl.getDeclaredMethods()) printMethod(m); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void printClass(Class<?> cl) { System.out.print(cl); printTypes(cl.getTypeParameters(), "<", ", ", ">", true); Type sc = cl.getGenericSuperclass(); if (sc != null) { System.out.print(" extends "); printType(sc, false); } printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false); System.out.println(); } public static void printMethod(Method m) { String name = m.getName(); System.out.print(Modifier.toString(m.getModifiers())); System.out.print(" "); printTypes(m.getTypeParameters(), "<", ", ", "> ", true); printType(m.getGenericReturnType(), false); System.out.print(" "); System.out.print(name); System.out.print("("); printTypes(m.getGenericParameterTypes(), "", ", ", "", false); System.out.println(")"); } public static void printTypes(Type[] types, String pre, String sep, String suf, boolean isDefinition) { if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class })) return; if (types.length > 0) System.out.print(pre); for (int i = 0; i < types.length; i++) { if (i > 0) System.out.print(sep); printType(types[i], isDefinition); } if (types.length > 0) System.out.print(suf); } public static void printType(Type type, boolean isDefinition) { if (type instanceof Class) { Class<?> t = (Class<?>) type; System.out.print(t.getName()); } else if (type instanceof TypeVariable) { TypeVariable<?> t = (TypeVariable<?>) type; System.out.print(t.getName()); if (isDefinition) printTypes(t.getBounds(), " extends ", " & ", "", false); } else if (type instanceof WildcardType) { WildcardType t = (WildcardType) type; System.out.print("?"); printTypes(t.getUpperBounds(), " extends ", " & ", "", false); printTypes(t.getLowerBounds(), " super ", " & ", "", false); } else if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) type; Type owner = t.getOwnerType(); if (owner != null) { printType(owner, false); System.out.print("."); } printType(t.getRawType(), false); printTypes(t.getActualTypeArguments(), "<", ", ", ">", false); } else if (type instanceof GenericArrayType) { GenericArrayType t = (GenericArrayType) type; System.out.print(""); printType(t.getGenericComponentType(), isDefinition); System.out.print("[]"); } } }
运行结果如下
java核心编程中的反射笔记。欢迎评论。
相关推荐
Java 反射详解
java java反射 反射 详解 java反射详解
java反射详解
java反射详解,详细说明java反射内部机制,适合初学者。
java反射 详解 入门到掌握 自己认为是很好的东东
Java 反射详解(包含私有方法属性的调用)
50页PPT详细讲解了反射与动态代理;强烈推荐。
简单的来说,反射机制指的是程序在运行时能够获取自身的信息。在java中,只要给定类的名字,那么就可以通过反射机制来获得类的所有信息。
}然后继续运行上面的程序,会出现:java.lang.InstantiationException: Reflect.Person at java.lan
java反射原理详解
java反射机制详解与应用
(通过反射获取无参构造方法并使用) (通过反射获取带参构造方法并使用) (通过反射获取私有构造方法并使用) (通过反射获取成员变量并使用) (通过反射获取无参无返回值成员方法并使用) (通过反射获取带参带返回值成员...
JAVA反射详解。 Reflection是Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查,或者说"自审",并能直接操作程序的内部属性。
Java Reflection (JAVA反射)详解
比较详细讲述了java的反射机制,收获颇丰。希望大家能够共同学习,一起进步。
java反射机制的详细描述
主要介绍了Java反射机制,首先简单介绍了反射机制的预备知识,进一步分析了Java反射机制的原理、实现技巧与应用方法,需要的朋友可以参考下