Java反射的详细学习与实例

Java反射的详细学习与实例_第1张图片

java.lang

Class Class

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

方法

    • All Methods  Static Methods  Instance Methods  Concrete Methods 
      Modifier and Type Method and Description
       Class asSubclass(Class clazz)

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

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

      T cast(Object obj)

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

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

      boolean desiredAssertionStatus()

      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对象表示的实体的超接口。

      AnnotatedType getAnnotatedSuperclass()

      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
      getAnnotation(Class 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[]
      getAnnotationsByType(Class annotationClass)

      Returns annotations that are associated with this element.

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

      String getCanonicalName()

      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对象所表示的类的成员。

      ClassLoader getClassLoader()

      Returns the class loader for the class.

      返回该类的类加载器。

      Class getComponentType()

      Returns the Class representing the component type of an array.

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

      Constructor 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
      getDeclaredAnnotation(Class 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[]
      getDeclaredAnnotationsByType(Class 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 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对象表示的类或接口的指定构造函数。

      Field getDeclaredField(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.

      Method getDeclaredMethod(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.

      Method getEnclosingMethod()

      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.

      Field getField(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.

      Type getGenericSuperclass()

      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.

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

      Method getMethod(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对象表示的类或接口的所有公共方法,包括由该类或接口声明的方法以及从超类和超接口继承的方法。

      int getModifiers()

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

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

      String getName()

      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)的名称。

      Package getPackage()

      Gets the package for this class.

      获取此类的包。

      ProtectionDomain getProtectionDomain()

      Returns the ProtectionDomain of this class.

      返回此类的ProtectionDomain。

      URL getResource(String name)

      Finds a resource with a given name.

      InputStream getResourceAsStream(String name)

      Finds a resource with a given name.

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

      Object[] getSigners()

      Gets the signers of this class.

      获取此类的签名者。

      String getSimpleName()

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

      Class getSuperclass()

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

      String getTypeName()

      Return an informative string for the name of this type.

      TypeVariable>[] 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对象表示的泛型声明所声明的类型变量。

      boolean isAnnotation()

      Returns true if this Class object represents an annotation type.

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

      boolean isAnnotationPresent(Class annotationClass)

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

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

      boolean isAnonymousClass()

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

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

      boolean isArray()

      Determines if this Class object represents an array class.

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

      boolean isAssignableFrom(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参数表示的类或接口相同,或者是该类或接口的超类或超接口。

      boolean isEnum()

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

      boolean isInstance(Object obj)

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

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

      boolean isInterface()

      Determines if the specified Class object represents an interface type.

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

      boolean isLocalClass()

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

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

      boolean isMemberClass()

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

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

      boolean isPrimitive()

      Determines if the specified Class object represents a primitive type.

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

      boolean isSynthetic()

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

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

      T newInstance()

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

      String toGenericString()

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

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

      String toString()

      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反射的详细学习与实例_第2张图片 

 

Java反射的详细学习与实例_第3张图片 

      • java.lang.reflect.Field
  • public final class Field
    extends AccessibleObject
    implements Member
    • Modifier and Type Method and Description
      boolean equals(Object obj)

      Compares this Field against the specified object.

      Object get(Object obj)

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

      AnnotatedType getAnnotatedType()

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


      T
      getAnnotation(Class annotationClass)

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


      T[]
      getAnnotationsByType(Class annotationClass)

      Returns annotations that are associated with this element.

      boolean getBoolean(Object obj)

      Gets the value of a static or instance boolean field.

      byte getByte(Object obj)

      Gets the value of a static or instance byte field.

      char getChar(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对象。

      double getDouble(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.

      float getFloat(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.

      Type getGenericType()

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

      int getInt(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.

      long getLong(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.

      int getModifiers()

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

      String getName()

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

      short getShort(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对象表示的字段的声明类型。

      int hashCode()

      Returns a hashcode for this Field.

      boolean isEnumConstant()

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

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

      boolean isSynthetic()

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

      void set(Object obj, Object value)

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

      void setBoolean(Object obj, boolean z)

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

      void setByte(Object obj, byte b)

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

      void setChar(Object obj, char c)

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

      void setDouble(Object obj, double d)

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

      void setFloat(Object obj, float f)

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

      void setInt(Object obj, int i)

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

      void setLong(Object obj, long l)

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

      void setShort(Object obj, short s)

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

      String toGenericString()

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

      String toString()

      Returns a string describing this Field.

 

        • java.lang.reflect.Method
  • public final class Method
    extends Executable
    • All Methods  Instance Methods  Concrete Methods 
      Modifier and Type Method and Description
      boolean equals(Object obj)

      Compares this Method against the specified object.

      AnnotatedType getAnnotatedReturnType()

      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
      getAnnotation(Class 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.

      Object getDefaultValue()

      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.

      Type getGenericReturnType()

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

      int getModifiers()

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

      String getName()

      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.

      int getParameterCount()

      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[] 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.

      int hashCode()

      Returns a hashcode for this Method.

      Object invoke(Object obj, Object... args)

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

      boolean isBridge()

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

      boolean isDefault()

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

      boolean isSynthetic()

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

      boolean isVarArgs()

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

      String toGenericString()

      Returns a string describing this Method, including type parameters.

      String toString()

      Returns a string describing this Method.

 

        • java.lang.reflect.Constructor
  • public final class Constructor
    extends Executable
    • Modifier and Type Method and Description
      boolean equals(Object obj)

      Compares this Constructor against the specified object.

      AnnotatedType getAnnotatedReceiverType()

      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.

      AnnotatedType getAnnotatedReturnType()

      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
      getAnnotation(Class 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.

      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.

      int getModifiers()

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

      String getName()

      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.

      int getParameterCount()

      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>[] 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.

      int hashCode()

      Returns a hashcode for this Constructor.

      boolean isSynthetic()

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

      boolean isVarArgs()

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

      T newInstance(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.

      String toGenericString()

      Returns a string describing this Constructor, including type parameters.

      String toString()

      Returns a string describing this Constructor.

 

 

    • java.lang.reflect.Modifier
  • public class Modifier
    extends Object
    • Modifier and Type Field and Description
      static int ABSTRACT

      The int value representing the abstract modifier.

      static int FINAL

      The int value representing the final modifier.

      static int INTERFACE

      The int value representing the interface modifier.

      static int NATIVE

      The int value representing the native modifier.

      static int PRIVATE

      The int value representing the private modifier.

      static int PROTECTED

      The int value representing the protected modifier.

      static int PUBLIC

      The int value representing the public modifier.

      static int STATIC

      The int value representing the static modifier.

      static int STRICT

      The int value representing the strictfp modifier.

      static int SYNCHRONIZED

      The int value representing the synchronized modifier.

      static int TRANSIENT

      The int value representing the transient modifier.

      static int VOLATILE

      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;j0) System.out.println(modifiers+" ");
	 		System.out.print(retType.getName()+" "+name+"(");

	 		//print parameter types 
	 		Class[]  paramTypes=m.getParameterTypes();
	 		for(int j=0;j0) 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
  • public class AccessibleObject
    extends Object
    implements AnnotatedElement

作用如下

  • 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 
      Modifier Constructor and Description
      protected AccessibleObject()

      Constructor: only used by the Java Virtual Machine.

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

    • All Methods  Static Methods  Instance Methods  Concrete Methods 
      Modifier and Type Method and Description

      T
      getAnnotation(Class 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[]
      getAnnotationsByType(Class annotationClass)

      Returns annotations that are associated with this element.

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


      T
      getDeclaredAnnotation(Class 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[]
      getDeclaredAnnotationsByType(Class annotationClass)

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

      boolean isAccessible()

      Get the value of the accessible flag for this object.

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

      boolean isAnnotationPresent(Class annotationClass)

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

      static void setAccessible(AccessibleObject[] array, boolean flag)

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

      void setAccessible(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 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 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;i0) 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 squares=new ArrayList<>();
for(int i=1;i<=5;i++)
   squares.add(i*i);
System.out.println(new ObjectAnalyzer().toString(squares));
	 }
}

 

运行结果

 

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

Java反射的详细学习与实例_第4张图片 

Java反射的详细学习与实例_第5张图片 

下面程序显示两个扩展数组的方法。请注意,将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反射的详细学习与实例_第6张图片

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 Type Method and Description
      static Object get(Object array, int index)

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

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

      static boolean getBoolean(Object array, int index)

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

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

      static byte getByte(Object array, int index)

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

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

      static char getChar(Object array, int index)

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

      static double getDouble(Object array, int index)

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

      static float getFloat(Object array, int index)

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

      static int getInt(Object array, int index)

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

      static int getLength(Object array)

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

      static long getLong(Object array, int index)

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

      static short getShort(Object array, int index)

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

      static Object newInstance(Class componentType, int... dimensions)

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

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

      static Object newInstance(Class componentType, int length)

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

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

      static void set(Object array, int index, Object value)

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

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

      static void setBoolean(Object array, int index, boolean z)

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

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

      static void setByte(Object array, int index, byte b)

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

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

      static void setChar(Object array, int index, char c)

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

      static void setDouble(Object array, int index, double d)

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

      static void setFloat(Object array, int index, float f)

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

      static void setInt(Object array, int index, int i)

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

      static void setLong(Object array, int index, long l)

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

      static void setShort(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

  • public final class Method
    extends Executable
    • All Methods  Instance Methods  Concrete Methods 
      Modifier and Type Method and Description
      boolean equals(Object obj)

      Compares this Method against the specified object.

      AnnotatedType getAnnotatedReturnType()

      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
      getAnnotation(Class 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.

      Object getDefaultValue()

      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.

      Type getGenericReturnType()

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

      int getModifiers()

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

      String getName()

      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.

      int getParameterCount()

      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[] 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.

      int hashCode()

      Returns a hashcode for this Method.

      Object invoke(Object obj, Object... args)

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

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

      boolean isBridge()

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

      boolean isDefault()

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

      boolean isSynthetic()

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

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

      boolean isVarArgs()

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

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

      String toGenericString()

      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;
	}

}

 

运行结果

Java反射的详细学习与实例_第7张图片

 

 

你可能感兴趣的:(Java反射的详细学习与实例)