java 反射1 Class

来源:互联网 发布:音视频转换器mac 编辑:程序博客网 时间:2024/06/06 17:10

Java 反射API提供了一个简单的,类型安全的api用来支持类和对象的内省。api可以用来:

  • 构建新的类实例和数组。
  • 访问和修改对象和类的域。
  • 调用对象和类的方法。
  • 访问和修改数组的元素。
反射api定义了类和方法:
  • 三个类-Field,Method,Constructor。
  • Class类,提供构造一个Field,Method,Constructor类的实例。
  • Array类,提供方法动太态构建和访问Java arrays。
  • Modifier类,包含了所有修饰符的声明,包含了方法用来解码修饰符。
  • InvocationTargetException类,包装了exceptions,被反射方法和构造器抛出。
  • AccessibleObject 和 ReflectPermission类,提供一个机制来抑制标准Java访问权限。
java.lang包下的一些部分也支持反射:
  • Static fields that hold instances of the class Class. These represent the primitive Java types booleanbytecharshortintlongfloat, and double, and the keyword void, at run-time. 
  • An uninstantiable placeholder class-Void-to hold a reference to the Class object representing the keyword void
性能开销
由于反射操作是动态解决的,当前的java虚拟机还无法执行优化。因此,反射操作比非反射要慢,应当避免频繁的使用。

java.lang.Class是所有反射api的入口。java.lang.reflect包中的所有类都没有公有的构造器。获取这些类,有必要调用Class类的适当的方法。

Object.getClass()

import java.util.HashSet;import java.util.Set;Set<String> s = new HashSet<String>();Class c = s.getClass();

byte[] bytes = new byte[1024];Class c = bytes.getClass();
enum E { A, B }Class c = A.getClass();
Class c = System.console().getClass();
Class c = "foo".getClass();

The .class Syntax

boolean b;Class c = b.getClass();   // compile-time errorClass c = boolean.class;  // correct
Class c = java.io.PrintStream.class;
Class c = int[][][].class;

Class.forName()

Class c = Class.forName("com.duke.MyLocaleServiceProvider");
Class cDoubleArray = Class.forName("[D");same as double[].classClass cStringArray = Class.forName("[[Ljava.lang.String;"); identical to String[][].class

TYPE Field for Primitive Type Wrappers

Class c = Double.TYPE;
Class c = Void.TYPE;
每个包装类能获取一个TYPE域,和原始类型的class一样。

Returns the super class for the given class.
Class.getSuperclass()
Class c = javax.swing.JButton.class.getSuperclass();

Returns all the public classes, interfaces, and enums that are members of the class including inherited members.
Class.getClasses()
Class<?>[] c = Character.class.getClasses();

Returns all of the classes interfaces, and enums that are explicitly declared in this class.
Class.getDeclaredClasses()
Class<?>[] c = Character.class.getDeclaredClasses();
Returns the Class in which these members were declared. 
Class.getDeclaringClass()
java.lang.reflect.Field.getDeclaringClass()
java.lang.reflect.Method.getDeclaringClass()
java.lang.reflect.Constructor.getDeclaringClass()
Returns the immediately enclosing class of the class.
Class.getEnclosingClass()
一个官方例子:
import java.lang.annotation.Annotation;import java.lang.reflect.Modifier;import java.lang.reflect.Type;import java.lang.reflect.TypeVariable;import java.util.Arrays;import java.util.ArrayList;import java.util.List;import static java.lang.System.out;public class ClassDeclarationSpy {    public static void main(String... args) {try {    Class<?> c = Class.forName(args[0]);    out.format("Class:%n  %s%n%n", c.getCanonicalName());    out.format("Modifiers:%n  %s%n%n",       Modifier.toString(c.getModifiers()));    out.format("Type Parameters:%n");    TypeVariable[] tv = c.getTypeParameters();    if (tv.length != 0) {out.format("  ");for (TypeVariable t : tv)    out.format("%s ", t.getName());out.format("%n%n");    } else {out.format("  -- No Type Parameters --%n%n");    }    out.format("Implemented Interfaces:%n");    Type[] intfs = c.getGenericInterfaces();    if (intfs.length != 0) {for (Type intf : intfs)    out.format("  %s%n", intf.toString());out.format("%n");    } else {out.format("  -- No Implemented Interfaces --%n%n");    }    out.format("Inheritance Path:%n");    List<Class> l = new ArrayList<Class>();    printAncestor(c, l);    if (l.size() != 0) {for (Class<?> cl : l)    out.format("  %s%n", cl.getCanonicalName());out.format("%n");    } else {out.format("  -- No Super Classes --%n%n");    }    out.format("Annotations:%n");    Annotation[] ann = c.getAnnotations();    if (ann.length != 0) {for (Annotation a : ann)    out.format("  %s%n", a.toString());out.format("%n");    } else {out.format("  -- No Annotations --%n%n");    }        // production code should handle this exception more gracefully} catch (ClassNotFoundException x) {    x.printStackTrace();}    }    private static void printAncestor(Class<?> c, List<Class> l) {Class<?> ancestor = c.getSuperclass(); if (ancestor != null) {    l.add(ancestor);    printAncestor(ancestor, l); }    }}
运行 
java ClassDeclarationSpy java.util.concurrent.ConcurrentNavigableMap

Class:  java.util.concurrent.ConcurrentNavigableMapModifiers:  public abstract interfaceType Parameters:  K V Implemented Interfaces:  java.util.concurrent.ConcurrentMap<K, V>  java.util.NavigableMap<K, V>Inheritance Path:  -- No Super Classes --Annotations:  -- No Annotations --

Class Methods for Locating FieldsClass APIList of members?Inherited members?Private members? getDeclaredField()nonoyesgetField()noyesnogetDeclaredFields()yesnoyesgetFields()yesyesno


Class Methods for Locating MethodsClass APIList of members?Inherited members?Private members?getDeclaredMethod()nonoyesgetMethod()noyesnogetDeclaredMethods()yesnoyesgetMethods()yesyesno


Class Methods for Locating ConstructorsClass APIList of members?Inherited members?Private members?getDeclaredConstructor()noN/A1yesgetConstructor()noN/A1nogetDeclaredConstructors()yesN/A1yesgetConstructors()yesN/A1no

一个官方的例子
import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Member;import static java.lang.System.out;enum ClassMember { CONSTRUCTOR, FIELD, METHOD, CLASS, ALL }public class ClassSpy {    public static void main(String... args) {try {    Class<?> c = Class.forName(args[0]);    out.format("Class:%n  %s%n%n", c.getCanonicalName());    Package p = c.getPackage();    out.format("Package:%n  %s%n%n",       (p != null ? p.getName() : "-- No Package --"));    for (int i = 1; i < args.length; i++) {switch (ClassMember.valueOf(args[i])) {case CONSTRUCTOR:    printMembers(c.getConstructors(), "Constructor");    break;case FIELD:    printMembers(c.getFields(), "Fields");    break;case METHOD:    printMembers(c.getMethods(), "Methods");    break;case CLASS:    printClasses(c);    break;case ALL:    printMembers(c.getConstructors(), "Constuctors");    printMembers(c.getFields(), "Fields");    printMembers(c.getMethods(), "Methods");    printClasses(c);    break;default:    assert false;}    }        // production code should handle these exceptions more gracefully} catch (ClassNotFoundException x) {    x.printStackTrace();}    }    private static void printMembers(Member[] mbrs, String s) {out.format("%s:%n", s);for (Member mbr : mbrs) {    if (mbr instanceof Field)out.format("  %s%n", ((Field)mbr).toGenericString());    else if (mbr instanceof Constructor)out.format("  %s%n", ((Constructor)mbr).toGenericString());    else if (mbr instanceof Method)out.format("  %s%n", ((Method)mbr).toGenericString());}if (mbrs.length == 0)    out.format("  -- No %s --%n", s);out.format("%n");    }    private static void printClasses(Class<?> c) {out.format("Classes:%n");Class<?>[] clss = c.getClasses();for (Class<?> cls : clss)    out.format("  %s%n", cls.getCanonicalName());if (clss.length == 0)    out.format("  -- No member interfaces, classes, or enums --%n");out.format("%n");    }}

$ java ClassSpy java.lang.ClassCastException CONSTRUCTORClass:  java.lang.ClassCastExceptionPackage:  java.langConstructor:  public java.lang.ClassCastException()  public java.lang.ClassCastException(java.lang.String)






0 0
原创粉丝点击