Java反射的详细学习与实例

java.lang

Class Class<T>

  • public final class Class<T>
    extends Object
    implements Serializable, GenericDeclaration, Type, AnnotatedElement

方法

    • All Methods  Static Methods  Instance Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      <U> Class<? extends U>asSubclass(Class<U> clazz)

      Casts this Class object to represent a subclass of the class represented by the specified class object.

      强制转换此Class对象以表示由指定的class对象表示的类的子类。

      Tcast(Object obj)

      Casts an object to the class or interface represented by this Class object.

      将对象强制转换为此类对象表示的类或接口。

      booleandesiredAssertionStatus()

      Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.

      返回在调用此方法时要初始化的断言状态。

      static Class<?>forName(String className)

      Returns the Class object associated with the class or interface with the given string name.

      使用给定的字符串名称返回与类或接口关联的Class对象。

      static Class<?>forName(String name, boolean initialize, ClassLoader loader)

      Returns the Class object associated with the class or interface with the given string name, using the given class loader.

      使用给定的类加载器返回与具有给定字符串名称的类或接口关联的Class对象。

      AnnotatedType[]getAnnotatedInterfaces()

      Returns an array of AnnotatedType objects that represent the use of types to specify superinterfaces of the entity represented by this Class object.

      返回一个AnnotatedType对象数组,该对象表示使用类型指定此Class对象表示的实体的超接口。

      AnnotatedTypegetAnnotatedSuperclass()

      Returns an AnnotatedType object that represents the use of a type to specify the superclass of the entity represented by this Class object.

      返回一个AnnotatedType对象,该对象表示使用一种类型来指定此Class对象表示的实体的超类。

      <A extends Annotation>
      A
      getAnnotation(Class<A> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      如果存在这样的注释,则返回指定类型的该元素的注释,否则为null。

      Annotation[]getAnnotations()

      Returns annotations that are present on this element.

      返回此元素上存在的注释。

      <A extends Annotation>
      A[]
      getAnnotationsByType(Class<A> annotationClass)

      Returns annotations that are associated with this element.

      返回与此元素关联的注释。

      StringgetCanonicalName()

      Returns the canonical name of the underlying class as defined by the Java Language Specification.

      返回Java语言规范定义的基础类的规范名称。

      Class<?>[]getClasses()

      Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.

      返回一个包含Class对象的数组,该Class对象表示所有公共类和接口,这些公共类和接口都是此Class对象所表示的类的成员。

      ClassLoadergetClassLoader()

      Returns the class loader for the class.

      返回该类的类加载器。

      Class<?>getComponentType()

      Returns the Class representing the component type of an array.

      返回表示数组的组件类型的Class。

      Constructor<T>getConstructor(Class<?>... parameterTypes)

      Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

      返回一个Constructor构造函数对象,该对象反映此Class对象表示的类的指定公共构造函数。

      Constructor<?>[]getConstructors()

      Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

      <A extends Annotation>
      A
      getDeclaredAnnotation(Class<A> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is directly present, else null.

      返回一个数组,该数组包含构造函数对象,反映由这个类对象表示的类的所有公共构造函数。

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      返回直接存在于此元素上的注释。

      <A extends Annotation>
      A[]
      getDeclaredAnnotationsByType(Class<A> annotationClass)

      Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present.

      如果此类注释直接存在或间接存在,则返回指定类型的此元素的注解

      Class<?>[]getDeclaredClasses()

      Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.

      返回一个Class对象数组,该数组反映了所有声明为该Class对象表示的类成员的所有类和接口。

      Constructor<T>getDeclaredConstructor(Class<?>... parameterTypes)

      Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

      Constructor<?>[]getDeclaredConstructors()

      Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

      返回一个构造函数对象,该对象反映此Class对象表示的类或接口的指定构造函数。

      FieldgetDeclaredField(String name)

      Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

      Field[]getDeclaredFields()

      Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

      MethodgetDeclaredMethod(String name, Class<?>... parameterTypes)

      Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

      Method[]getDeclaredMethods()

      Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

      Class<?>getDeclaringClass()

      If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.

      Class<?>getEnclosingClass()

      Returns the immediately enclosing class of the underlying class.

      Constructor<?>getEnclosingConstructor()

      If this Class object represents a local or anonymous class within a constructor, returns a Constructor object representing the immediately enclosing constructor of the underlying class.

      MethodgetEnclosingMethod()

      If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class.

      T[]getEnumConstants()

      Returns the elements of this enum class or null if this Class object does not represent an enum type.

      FieldgetField(String name)

      Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

      Field[]getFields()

      Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

      返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问公共字段。

      Type[]getGenericInterfaces()

      Returns the Types representing the interfaces directly implemented by the class or interface represented by this object.

      TypegetGenericSuperclass()

      Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

      返回该类表示的实体的直接超类的Type(类,接口,基本类型或void)。

      Class<?>[]getInterfaces()

      Determines the interfaces implemented by the class or interface represented by this object.

      确定由该对象实现的接口或此对象表示的接口

      MethodgetMethod(String name, Class<?>... parameterTypes)

      Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

      返回一个Method对象,该对象反映此Class对象表示的类或接口的指定公共成员方法。

      Method[]getMethods()

      Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

      返回一个包含Method对象的数组,该对象反映此Class对象表示的类或接口的所有公共方法,包括由该类或接口声明的方法以及从超类和超接口继承的方法。

      intgetModifiers()

      Returns the Java language modifiers for this class or interface, encoded in an integer.

      返回此类或接口的Java语言修饰符,以整数编码。

      StringgetName()

      Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

      以String形式返回此Class对象表示的实体(类,接口,数组类,原始类型或void)的名称。

      PackagegetPackage()

      Gets the package for this class.

      获取此类的包。

      ProtectionDomaingetProtectionDomain()

      Returns the ProtectionDomain of this class.

      返回此类的ProtectionDomain。

      URLgetResource(String name)

      Finds a resource with a given name.

      InputStreamgetResourceAsStream(String name)

      Finds a resource with a given name.

      查找具有给定名称的资源。

      Object[]getSigners()

      Gets the signers of this class.

      获取此类的签名者。

      StringgetSimpleName()

      Returns the simple name of the underlying class as given in the source code.

      Class<? super T>getSuperclass()

      Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.

      StringgetTypeName()

      Return an informative string for the name of this type.

      TypeVariable<Class<T>>[]getTypeParameters()

      Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

      返回TypeVariable对象的数组,这些对象按声明顺序表示此GenericDeclaration对象表示的泛型声明所声明的类型变量。

      booleanisAnnotation()

      Returns true if this Class object represents an annotation type.

      如果此Class对象表示注释类型,则返回true。

      booleanisAnnotationPresent(Class<? extends Annotation> annotationClass)

      Returns true if an annotation for the specified type is present on this element, else false.

      如果此元素上存在指定类型的注释,则返回true,否则返回false。

      booleanisAnonymousClass()

      Returns true if and only if the underlying class is an anonymous class.

      当且仅当基础类是匿名类时,才返回true。

      booleanisArray()

      Determines if this Class object represents an array class.

      确定此Class对象是否表示数组类。

      booleanisAssignableFrom(Class<?> cls)

      Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

      确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是该类或接口的超类或超接口。

      booleanisEnum()

      Returns true if and only if this class was declared as an enum in the source code.

      booleanisInstance(Object obj)

      Determines if the specified Object is assignment-compatible with the object represented by this Class.

      确定指定的Object是否与此类表示的对象赋值兼容。

      booleanisInterface()

      Determines if the specified Class object represents an interface type.

      确定指定的Class对象是否表示接口类型。

      booleanisLocalClass()

      Returns true if and only if the underlying class is a local class.

      当且仅当基础类是本地类时,才返回true。

      booleanisMemberClass()

      Returns true if and only if the underlying class is a member class.

      当且仅当基础类是成员类时,才返回true。

      booleanisPrimitive()

      Determines if the specified Class object represents a primitive type.

      确定指定的Class对象是否表示基本类型。

      booleanisSynthetic()

      Returns true if this class is a synthetic class; returns false otherwise.

      如果此类是综合类,则返回true;否则,返回true。 否则返回false。

      TnewInstance()

      Creates a new instance of the class represented by this Class object.

      StringtoGenericString()

      Returns a string describing this Class, including information about modifiers and type parameters.

      返回描述此Class的字符串,包括有关修饰符和类型参数的信息。

      StringtoString()

      Converts the object to a string.

      将对象转换为字符串。

 

简单使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.*;
public class TestB{

	public static void main(String[] args) throws Exception{
		Random generator=new Random();
		Class cl=generator.getClass();
		String name=cl.getName();
		System.out.println(name);
		Class cl1=Class.forName("java.util.Random");
		System.out.println(cl1.getName());

	
	}
}

 

 

 

      • java.lang.reflect.Field
    • Modifier and TypeMethod and Description
      booleanequals(Object obj)

      Compares this Field against the specified object.

      Objectget(Object obj)

      Returns the value of the field represented by this Field, on the specified object.

      AnnotatedTypegetAnnotatedType()

      Returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field.

      <T extends Annotation>
      T
      getAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      <T extends Annotation>
      T[]
      getAnnotationsByType(Class<T> annotationClass)

      Returns annotations that are associated with this element.

      booleangetBoolean(Object obj)

      Gets the value of a static or instance boolean field.

      bytegetByte(Object obj)

      Gets the value of a static or instance byte field.

      chargetChar(Object obj)

      Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      返回直接存在于此元素上的注释。

      Class<?>getDeclaringClass()

      Returns the Class object representing the class or interface that declares the field represented by this Field object.

      返回表示声明此Field对象表示的字段的类或接口的Class对象。

      doublegetDouble(Object obj)

      Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion.

      floatgetFloat(Object obj)

      Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion.

      TypegetGenericType()

      Returns a Type object that represents the declared type for the field represented by this Field object.

      intgetInt(Object obj)

      Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.

      longgetLong(Object obj)

      Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.

      intgetModifiers()

      Returns the Java language modifiers for the field represented by this Field object, as an integer.

      StringgetName()

      Returns the name of the field represented by this Field object.

      shortgetShort(Object obj)

      Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion.

      Class<?>getType()

      Returns a Class object that identifies the declared type for the field represented by this Field object.

      返回一个Class对象,该对象标识此Field对象表示的字段的声明类型。

      inthashCode()

      Returns a hashcode for this Field.

      booleanisEnumConstant()

      Returns true if this field represents an element of an enumerated type; returns false otherwise.

      如果此字段表示枚举类型的元素,则返回true;否则,返回true。 否则返回false。

      booleanisSynthetic()

      Returns true if this field is a synthetic field; returns false otherwise.

      voidset(Object obj, Object value)

      Sets the field represented by this Field object on the specified object argument to the specified new value.

      voidsetBoolean(Object obj, boolean z)

      Sets the value of a field as a boolean on the specified object.

      voidsetByte(Object obj, byte b)

      Sets the value of a field as a byte on the specified object.

      voidsetChar(Object obj, char c)

      Sets the value of a field as a char on the specified object.

      voidsetDouble(Object obj, double d)

      Sets the value of a field as a double on the specified object.

      voidsetFloat(Object obj, float f)

      Sets the value of a field as a float on the specified object.

      voidsetInt(Object obj, int i)

      Sets the value of a field as an int on the specified object.

      voidsetLong(Object obj, long l)

      Sets the value of a field as a long on the specified object.

      voidsetShort(Object obj, short s)

      Sets the value of a field as a short on the specified object.

      StringtoGenericString()

      Returns a string describing this Field, including its generic type.

      StringtoString()

      Returns a string describing this Field.

 

        • java.lang.reflect.Method
    • All Methods  Instance Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      booleanequals(Object obj)

      Compares this Method against the specified object.

      AnnotatedTypegetAnnotatedReturnType()

      Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.

      <T extends Annotation>
      T
      getAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      Class<?>getDeclaringClass()

      Returns the Class object representing the class or interface that declares the executable represented by this object.

      ObjectgetDefaultValue()

      Returns the default value for the annotation member represented by this Method instance.

      Class<?>[]getExceptionTypes()

      Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.

      Type[]getGenericExceptionTypes()

      Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.

      Type[]getGenericParameterTypes()

      Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      TypegetGenericReturnType()

      Returns a Type object that represents the formal return type of the method represented by this Method object.

      intgetModifiers()

      Returns the Java language modifiers for the executable represented by this object.

      StringgetName()

      Returns the name of the method represented by this Method object, as a String.

      Annotation[][]getParameterAnnotations()

      Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.

      intgetParameterCount()

      Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

      Class<?>[]getParameterTypes()

      Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      Class<?>getReturnType()

      Returns a Class object that represents the formal return type of the method represented by this Method object.

      TypeVariable<Method>[]getTypeParameters()

      Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

      inthashCode()

      Returns a hashcode for this Method.

      Objectinvoke(Object obj, Object... args)

      Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

      booleanisBridge()

      Returns true if this method is a bridge method; returns false otherwise.

      booleanisDefault()

      Returns true if this method is a default method; returns false otherwise.

      booleanisSynthetic()

      Returns true if this executable is a synthetic construct; returns false otherwise.

      booleanisVarArgs()

      Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

      StringtoGenericString()

      Returns a string describing this Method, including type parameters.

      StringtoString()

      Returns a string describing this Method.

 

        • java.lang.reflect.Constructor<T>
  • public final class Constructor<T>
    extends Executable
    • Modifier and TypeMethod and Description
      booleanequals(Object obj)

      Compares this Constructor against the specified object.

      AnnotatedTypegetAnnotatedReceiverType()

      Returns an AnnotatedType object that represents the use of a type to specify the receiver type of the method/constructor represented by this Executable object.

      AnnotatedTypegetAnnotatedReturnType()

      Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.

      <T extends Annotation>
      T
      getAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      Class<T>getDeclaringClass()

      Returns the Class object representing the class or interface that declares the executable represented by this object.

      Class<?>[]getExceptionTypes()

      Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.

      Type[]getGenericExceptionTypes()

      Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.

      Type[]getGenericParameterTypes()

      Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      intgetModifiers()

      Returns the Java language modifiers for the executable represented by this object.

      StringgetName()

      Returns the name of this constructor, as a string.

      Annotation[][]getParameterAnnotations()

      Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.

      intgetParameterCount()

      Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

      Class<?>[]getParameterTypes()

      Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      TypeVariable<Constructor<T>>[]getTypeParameters()

      Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

      inthashCode()

      Returns a hashcode for this Constructor.

      booleanisSynthetic()

      Returns true if this executable is a synthetic construct; returns false otherwise.

      booleanisVarArgs()

      Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

      TnewInstance(Object... initargs)

      Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

      StringtoGenericString()

      Returns a string describing this Constructor, including type parameters.

      StringtoString()

      Returns a string describing this Constructor.

 

 

    • java.lang.reflect.Modifier
  • public class Modifier
    extends Object
    • Modifier and TypeField and Description
      static intABSTRACT

      The int value representing the abstract modifier.

      static intFINAL

      The int value representing the final modifier.

      static intINTERFACE

      The int value representing the interface modifier.

      static intNATIVE

      The int value representing the native modifier.

      static intPRIVATE

      The int value representing the private modifier.

      static intPROTECTED

      The int value representing the protected modifier.

      static intPUBLIC

      The int value representing the public modifier.

      static intSTATIC

      The int value representing the static modifier.

      static intSTRICT

      The int value representing the strictfp modifier.

      static intSYNCHRONIZED

      The int value representing the synchronized modifier.

      static intTRANSIENT

      The int value representing the transient modifier.

      static intVOLATILE

      The int value representing the volatile modifier.

 示例代码

 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
import java.util.*;
import java.lang.reflect.*;
/*
*This program uses reflection to print all features of a class
 */
public class TestB{

	public static void main(String[] args){
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.Date):");
	name=in.next();
}
try{
	Class cl=Class.forName(name);
	Class supercl=cl.getSuperclass();
	String modifiers=Modifier.toString(cl.getModifiers());
	if(modifiers.length()>0) System.out.println(modifiers+" ");
	System.out.println("class"+name);
	if(supercl !=null && supercl !=Object.class) System.out.println(" extends "+supercl.getName());
	System.out.print("\n{\n");
	printConstructors(cl);
	System.out.println();
	printMethods(cl);
	System.out.println();
	printFields(cl);
	System.out.println("}");
}catch(ClassNotFoundException e){
	e.printStackTrace();
}
System.exit(0);

	
	}
	/*
	*Print all constructors of a class
	 */
	 
	 public static void printConstructors(Class cl)
	 {
	 	Constructor[] constructors=cl.getDeclaredConstructors();
	 	for(Constructor c:constructors)
	 	{
	 		String name=c.getName();
	 		System.out.print(" ");
	 		String modifiers=Modifier.toString(c.getModifiers());
	 		if(modifiers.length()>0) System.out.print(modifiers+" ");
	 		System.out.print(name+"(");

	 		//print parameter types
	 		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(");");
	 	}
	 }
	 /*
	 *Prints all methods of a class
	  */
	 public static void printMethods(Class cl)
	 {
	 	Method[] methods=cl.getDeclaredMethods();
	 	for(Method m:methods)
	 	{
	 		Class retType=m.getReturnType();
	 		String name=m.getName();

	 		System.out.print(" ");
	 		String modifiers=Modifier.toString(m.getModifiers());
	 		if(modifiers.length()>0) System.out.println(modifiers+" ");
	 		System.out.print(retType.getName()+" "+name+"(");

	 		//print parameter types 
	 		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.print(");");
	 	}
	 }

	 /*
	 *Prints all fields of a class
	  */
	 public static void printFields(Class cl)
	 {
	 	Field[] fields=cl.getDeclaredFields();
	 	for(Field f:fields)
	 	{
	 		Class type=f.getType();
	 		String name=f.getName();
	 		System.out.print(" ");
	 		String modifiers=Modifier.toString(f.getModifiers());
	 		if(modifiers.length()>0) System.out.print(modifiers+" ");
	 		System.out.println(type.getName()+" "+name+";");
	 	}
	 }
}

 

运行结果

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
D:\java>java TestB
Enter class name(e.g. java.util.Date):
java.util.Random
public
classjava.util.Random

{
 public java.util.Random();
 public java.util.Random(long);

 protected
int next(int); private
void readObject(java.io.ObjectInputStream); private synchronized
void writeObject(java.io.ObjectOutputStream); public
int nextInt(); public
int nextInt(int); public
double nextDouble(); public
java.util.stream.DoubleStream doubles(double, double); public
java.util.stream.DoubleStream doubles(long, double, double); public
java.util.stream.DoubleStream doubles(long); public
java.util.stream.DoubleStream doubles(); private static
long initialScramble(long); final
double internalNextDouble(double, double); final
int internalNextInt(int, int); final
long internalNextLong(long, long); public
java.util.stream.IntStream ints(int, int); public
java.util.stream.IntStream ints(long, int, int); public
java.util.stream.IntStream ints(); public
java.util.stream.IntStream ints(long); public
java.util.stream.LongStream longs(long, long, long); public
java.util.stream.LongStream longs(long, long); public
java.util.stream.LongStream longs(); public
java.util.stream.LongStream longs(long); public
void nextBytes([B); public synchronized
double nextGaussian(); private
void resetSeed(long); private static
long seedUniquifier(); public synchronized
void setSeed(long); public
boolean nextBoolean(); public
float nextFloat(); public
long nextLong();
 static final long serialVersionUID;
 private final java.util.concurrent.atomic.AtomicLong seed;
 private static final long multiplier;
 private static final long addend;
 private static final long mask;
 private static final double DOUBLE_UNIT;
 static final java.lang.String BadBound;
 static final java.lang.String BadRange;
 static final java.lang.String BadSize;
 private static final java.util.concurrent.atomic.AtomicLong seedUniquifier;
 private double nextNextGaussian;
 private boolean haveNextNextGaussian;
 private static final [Ljava.io.ObjectStreamField; serialPersistentFields;
 private static final sun.misc.Unsafe unsafe;
 private static final long seedOffset;

 

 

    • java.lang.reflect.AccessibleObject

作用如下

  • The AccessibleObject class is the base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks--for public, default (package) access, protected, and private members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively.

    Setting the accessible flag in a reflected object permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate objects in a manner that would normally be prohibited.

    By default, a reflected object is not accessible.

简言之,就是可以设置权限,访问原本权限不足以访问的包,类,保护或私有的字段与方法

    • Constructors 
      ModifierConstructor and Description
      protected AccessibleObject()

      Constructor: only used by the Java Virtual Machine.

      构造函数:仅由Java虚拟机使用。

    • All Methods  Static Methods  Instance Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      <T extends Annotation>
      T
      getAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      Annotation[]getAnnotations()

      Returns annotations that are present on this element.

      <T extends Annotation>
      T[]
      getAnnotationsByType(Class<T> annotationClass)

      Returns annotations that are associated with this element.

      返回与此元素关联的注释。

      <T extends Annotation>
      T
      getDeclaredAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is directly present, else null.

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      <T extends Annotation>
      T[]
      getDeclaredAnnotationsByType(Class<T> annotationClass)

      Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present.

      booleanisAccessible()

      Get the value of the accessible flag for this object.

      获取此对象的可访问标志的值。

      booleanisAnnotationPresent(Class<? extends Annotation> annotationClass)

      Returns true if an annotation for the specified type is present on this element, else false.

      static voidsetAccessible(AccessibleObject[] array, boolean flag)

      Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

      voidsetAccessible(boolean flag)

      Set the accessible flag for this object to the indicated boolean value.

 

setAccessible方法是AccessibleObject类中的一个方法,它是Field,Method和Constructor类的公共超类。这个特性是为调试,持久存储和相似机制提供的。

下面程序编写一个可供任意类使用的通用toString方法。

可以使用toString方法查看任意对象的内部信息。例如,下面这个调用:

 

1
2
3
ArrayList<Integer> squares=new ArrayList<>();
for(int i=1;i<5;i++) squares.add(i*i);
System.out.println(new ObjectAnalyzer().toString(squares));

 

还可以使用通用的toString方法实现自己类中的toString方法,如下图所示:

 

1
2
3
4
5
public String toString()
{
	return new ObjectAnalyzer().toString(this);
}
这是一种公认的提供toString方法的手段,在编写程序时会发现,它是非常有用的。

 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

public class ObjectAnalyzer
{
	private ArrayList<Object> visited=new ArrayList<>();
	/*
	*Converts an object to a string representation that llists all fields.
	*@param obj an object
	*@return a string with the object's class name and all field names and values
	 */
	public String toString(Object obj)
	{
		if(obj==null) return "null";
		if(visited.contains(obj)) return "...";
		visited.add(obj);
		Class cl=obj.getClass();
		if(cl==String.class) return (String)obj;
		if(cl.isArray())
		{
			String r=cl.getComponentType()+"[]{";
			for(int i=0;i<Array.getLength(obj);i++)
			{
				if(i>0) r+=",";
				Object val=Array.get(obj,i);
				if(cl.getComponentType().isPrimitive()) r+=val;
				else r+=toString(val);
			}
			return r+"}";
		}
		String r=cl.getName();
		//inspect the fields of this class and all superclasses
		do{
			r+="]";
			Field[] fields=cl.getDeclaredFields();
			AccessibleObject.setAccessible(fields,true);
			//get the names and values of all fields
			for(Field f:fields)
			{
				if(!Modifier.isStatic(f.getModifiers()))
				{
					if(!r.endsWith("[")) r+=",";
					r+=f.getName()+"=";
					try
					{
						Class t=f.getType();
						Object val=f.get(obj);
						if(t.isPrimitive()) r+=val;
						else r+=toString(val);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			r+="]";
			cl=cl.getSuperclass();

		}
		while(cl !=null);
		return r;
	}

}

 

测试Demo

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import java.util.ArrayList;
/*
*This program uses reflection to spy on objects.
 */
public class TestB{

	public static void main(String[] args){
ArrayList<Integer> squares=new ArrayList<>();
for(int i=1;i<=5;i++)
   squares.add(i*i);
System.out.println(new ObjectAnalyzer().toString(squares));
	 }
}

 

运行结果

 

使用反射编写泛型数组代码

 

 

下面程序显示两个扩展数组的方法。请注意,将badCopyOf的返回值进行类型转换将会抛出一个异常。

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.lang.reflect.*;
import java.util.*;
/*
*This program demonstrates the use of reflection for manipulating arrays
 */
public class TestB{

	public static void main(String[] args){
         int[] a={1,2,3};
         a=(int[])goodCopyOf(a,10);
         System.out.println(Arrays.toString(a));

         String[] b={"Tom","Dick","Harry"};
         b=(String[])goodCopyOf(b,10);
         System.out.println(Arrays.toString(b));

         System.out.println("The following call will generate an exception.");
         b=(String[])badCopyOf(b,10);
	 }
	 /*
	 *This method attempts to grow an array by allocationg a new array and copying all elements.
	  */
	 public static Object[] badCopyOf(Object[] a,int newLength)
	 {
	 	Object[] newArray=new Object[newLength];
	 	System.arraycopy(a,0,newArray,0,Math.min(a.length,newLength));
	 	return newArray;
	 }
	 /*
	 *This method grows an array by allocating a new array of the same type and copying all elements.
	  */
	 public static Object goodCopyOf(Object a,int newLength)
	 {
	 	Class cl=a.getClass();
	 	if(!cl.isArray()) return null;
	 	Class componentType=cl.getComponentType();
	 	int length=Array.getLength(a);
	 	Object newArray=Array.newInstance(componentType,newLength);
	 	System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
	 	return newArray;
	 }
 }

 

运行结果

java.lang.reflect

Class Array

  • public final class Array
    extends Object
  • The Array class provides static methods to dynamically create and access Java arrays.

    Array permits widening conversions to occur during a get or set operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

 

    • All Methods  Static Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      static Objectget(Object array, int index)

      Returns the value of the indexed component in the specified array object.

      返回指定数组对象中索引组件的值。

      static booleangetBoolean(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a boolean.

      返回指定数组对象中索引组件的布尔值。

      static bytegetByte(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a byte.

      以字节为单位返回指定数组对象中索引组件的值。

      static chargetChar(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a char.

      static doublegetDouble(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a double.

      static floatgetFloat(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a float.

      static intgetInt(Object array, int index)

      Returns the value of the indexed component in the specified array object, as an int.

      static intgetLength(Object array)

      Returns the length of the specified array object, as an int.

      static longgetLong(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a long.

      static shortgetShort(Object array, int index)

      Returns the value of the indexed component in the specified array object, as a short.

      static ObjectnewInstance(Class<?> componentType, int... dimensions)

      Creates a new array with the specified component type and dimensions.

      创建具有指定组件类型和维度的新数组。

      static ObjectnewInstance(Class<?> componentType, int length)

      Creates a new array with the specified component type and length.

      创建具有指定组件类型和长度的新数组。

      static voidset(Object array, int index, Object value)

      Sets the value of the indexed component of the specified array object to the specified new value.

      将指定数组对象的索引组件的值设置为指定的新值

      static voidsetBoolean(Object array, int index, boolean z)

      Sets the value of the indexed component of the specified array object to the specified boolean value.

      将指定数组对象的索引组件的值设置为指定的布尔值

      static voidsetByte(Object array, int index, byte b)

      Sets the value of the indexed component of the specified array object to the specified byte value.

      将指定数组对象的索引组件的值设置为指定的字节值。 

      static voidsetChar(Object array, int index, char c)

      Sets the value of the indexed component of the specified array object to the specified char value.

      static voidsetDouble(Object array, int index, double d)

      Sets the value of the indexed component of the specified array object to the specified double value.

      static voidsetFloat(Object array, int index, float f)

      Sets the value of the indexed component of the specified array object to the specified float value.

      static voidsetInt(Object array, int index, int i)

      Sets the value of the indexed component of the specified array object to the specified int value.

      static voidsetLong(Object array, int index, long l)

      Sets the value of the indexed component of the specified array object to the specified long value.

      static voidsetShort(Object array, int index, short s)

      Sets the value of the indexed component of the specified array object to the specified short value.

 

调用任意方法

 

java.lang.reflect

Class Method

    • All Methods  Instance Methods  Concrete Methods 
      Modifier and TypeMethod and Description
      booleanequals(Object obj)

      Compares this Method against the specified object.

      AnnotatedTypegetAnnotatedReturnType()

      Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.

      <T extends Annotation>
      T
      getAnnotation(Class<T> annotationClass)

      Returns this element's annotation for the specified type if such an annotation is present, else null.

      Annotation[]getDeclaredAnnotations()

      Returns annotations that are directly present on this element.

      Class<?>getDeclaringClass()

      Returns the Class object representing the class or interface that declares the executable represented by this object.

      ObjectgetDefaultValue()

      Returns the default value for the annotation member represented by this Method instance.

      Class<?>[]getExceptionTypes()

      Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.

      Type[]getGenericExceptionTypes()

      Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.

      Type[]getGenericParameterTypes()

      Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      TypegetGenericReturnType()

      Returns a Type object that represents the formal return type of the method represented by this Method object.

      intgetModifiers()

      Returns the Java language modifiers for the executable represented by this object.

      StringgetName()

      Returns the name of the method represented by this Method object, as a String.

      Annotation[][]getParameterAnnotations()

      Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.

      intgetParameterCount()

      Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

      Class<?>[]getParameterTypes()

      Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

      Class<?>getReturnType()

      Returns a Class object that represents the formal return type of the method represented by this Method object.

      TypeVariable<Method>[]getTypeParameters()

      Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

      inthashCode()

      Returns a hashcode for this Method.

      Objectinvoke(Object obj, Object... args)

      Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

      在具有指定参数的指定对象上调用由此方法对象表示的基础方法。

      booleanisBridge()

      Returns true if this method is a bridge method; returns false otherwise.

      booleanisDefault()

      Returns true if this method is a default method; returns false otherwise.

      booleanisSynthetic()

      Returns true if this executable is a synthetic construct; returns false otherwise.

      如果该可执行文件是合成结构,则返回true;否则返回false。

      booleanisVarArgs()

      Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

      如果该可执行文件被声明为具有可变数量的参数,则返回true;否则返回false。

      StringtoGenericString()

      Returns a string describing this Method, including type parameters.

      返回描述此方法的字符串,包括类型参数。

      String

      toString()

      Returns a string describing this Method.

      返回描述此方法的字符串。

       

        

 

 

1
2
3
4
5
6
7
8
9
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectServiceImpl {
	public void sayHello(String name) {
		System.err.println("Hello " + name);
	}

}

 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.lang.reflect.InvocationTargetException;

public class ReflectServiceImpl2 {
	private String name;

	public ReflectServiceImpl2(String name) {
		this.name = name;
	}

	public void sayHello() {
		System.err.println("hello " + name);
	}
	
	public ReflectServiceImpl2 getInstance() {
	    ReflectServiceImpl2 object = null;
	    try {
	        object = 
	            (ReflectServiceImpl2) 
	            Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl2").
	            getConstructor(String.class).newInstance("张三");
	    } catch (ClassNotFoundException | InstantiationException 
	                | IllegalAccessException | NoSuchMethodException 
	                | SecurityException | IllegalArgumentException 
	                | InvocationTargetException ex) {
	            ex.printStackTrace();
	    }
	    return object;
	}
}

 

测试Demo

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ReflectServiceImpl one=(ReflectServiceImpl)getInstance();
		one.sayHello("test");

		reflectMethod();
		reflect();

	}
	
	public static ReflectServiceImpl getInstance() {
		ReflectServiceImpl object = null;
		try {
			object = (ReflectServiceImpl) Class.forName("ReflectServiceImpl")
					.newInstance();
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
			ex.printStackTrace();
		}
		return object;
	}

	public static Object  reflectMethod() {
		Object returnObj = null;
		ReflectServiceImpl target = new ReflectServiceImpl();
		try {
			Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
			returnObj = method.invoke(target, "zhangsan");
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException ex) {
			ex.printStackTrace();
		}
		return returnObj;
	}

	public static Object reflect() {
		ReflectServiceImpl object = null;
		try {
			object = (ReflectServiceImpl) Class.forName("ReflectServiceImpl")
					.newInstance();
			Method method = object.getClass().getMethod("sayHello", String.class);
			method.invoke(object, "zhangsan");
		} catch (NoSuchMethodException | SecurityException | ClassNotFoundException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
			ex.printStackTrace();
		}
		return object;
	}

}

 

运行结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值