java.lang
public final class Class
extends Object
implements Serializable, GenericDeclaration, Type, AnnotatedElement
方法
Modifier and Type | Method and Description |
---|---|
Class extends U> |
asSubclass(Class clazz) Casts this 强制转换此Class对象以表示由指定的class对象表示的类的子类。 |
T |
cast(Object obj) Casts an object to the class or interface represented by this 将对象强制转换为此类对象表示的类或接口。 |
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对象。 |
static Class> |
forName(String name, boolean initialize, ClassLoader loader) Returns the 使用给定的类加载器返回与具有给定字符串名称的类或接口关联的Class对象。 |
AnnotatedType[] |
getAnnotatedInterfaces() Returns an array of 返回一个AnnotatedType对象数组,该对象表示使用类型指定此Class对象表示的实体的超接口。 |
AnnotatedType |
getAnnotatedSuperclass() Returns an 返回一个AnnotatedType对象,该对象表示使用一种类型来指定此Class对象表示的实体的超类。 |
|
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. 返回此元素上存在的注释。 |
|
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对象的数组,该Class对象表示所有公共类和接口,这些公共类和接口都是此Class对象所表示的类的成员。 |
ClassLoader |
getClassLoader() Returns the class loader for the class. 返回该类的类加载器。 |
Class> |
getComponentType() Returns the 返回表示数组的组件类型的Class。 |
Constructor |
getConstructor(Class>... parameterTypes) Returns a 返回一个 |
Constructor>[] |
getConstructors() Returns an array containing |
|
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. 返回直接存在于此元素上的注释。 |
|
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对象数组,该数组反映了所有声明为该Class对象表示的类成员的所有类和接口。 |
Constructor |
getDeclaredConstructor(Class>... parameterTypes) Returns a |
Constructor>[] |
getDeclaredConstructors() Returns an array of 返回一个构造函数对象,该对象反映此Class对象表示的类或接口的指定构造函数。 |
Field |
getDeclaredField(String name) Returns a |
Field[] |
getDeclaredFields() Returns an array of |
Method |
getDeclaredMethod(String name, Class>... parameterTypes) Returns a |
Method[] |
getDeclaredMethods() Returns an array containing |
Class> |
getDeclaringClass() If the class or interface represented by this |
Class> |
getEnclosingClass() Returns the immediately enclosing class of the underlying class. |
Constructor> |
getEnclosingConstructor() If this |
Method |
getEnclosingMethod() If this |
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[] |
getFields() Returns an array containing 返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问公共字段。 |
Type[] |
getGenericInterfaces() Returns the |
Type |
getGenericSuperclass() Returns the 返回该类表示的实体的直接超类的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对象,该对象反映此Class对象表示的类或接口的指定公共成员方法。 |
Method[] |
getMethods() Returns an array containing 返回一个包含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 以String形式返回此Class对象表示的实体(类,接口,数组类,原始类型或void)的名称。 |
Package |
getPackage() Gets the package for this class. 获取此类的包。 |
ProtectionDomain |
getProtectionDomain() Returns the 返回此类的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 super T> |
getSuperclass() Returns the |
String |
getTypeName() Return an informative string for the name of this type. |
TypeVariable |
getTypeParameters() Returns an array of 返回TypeVariable对象的数组,这些对象按声明顺序表示此GenericDeclaration对象表示的泛型声明所声明的类型变量。 |
boolean |
isAnnotation() Returns true if this 如果此Class对象表示注释类型,则返回true。 |
boolean |
isAnnotationPresent(Class extends Annotation> annotationClass) Returns true if an annotation for the specified type is present on this element, else false. 如果此元素上存在指定类型的注释,则返回true,否则返回false。 |
boolean |
isAnonymousClass() Returns 当且仅当基础类是匿名类时,才返回true。 |
boolean |
isArray() Determines if this 确定此Class对象是否表示数组类。 |
boolean |
isAssignableFrom(Class> cls) Determines if the class or interface represented by this 确定此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是否与此类表示的对象赋值兼容。 |
boolean |
isInterface() Determines if the specified 确定指定的Class对象是否表示接口类型。 |
boolean |
isLocalClass() Returns 当且仅当基础类是本地类时,才返回true。 |
boolean |
isMemberClass() Returns 当且仅当基础类是成员类时,才返回true。 |
boolean |
isPrimitive() Determines if the specified 确定指定的Class对象是否表示基本类型。 |
boolean |
isSynthetic() Returns 如果此类是综合类,则返回true;否则,返回true。 否则返回false。 |
T |
newInstance() Creates a new instance of the class represented by this |
String |
toGenericString() Returns a string describing this 返回描述此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()); } } |
public final class Field extends AccessibleObject implements Member
Modifier and Type | Method and Description |
---|---|
boolean |
equals(Object obj) Compares this |
Object |
get(Object obj) Returns the value of the field represented by this |
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. |
|
getAnnotation(Class Returns this element's annotation for the specified type if such an annotation is present, else null. |
|
getAnnotationsByType(Class Returns annotations that are associated with this element. |
boolean |
getBoolean(Object obj) Gets the value of a static or instance |
byte |
getByte(Object obj) Gets the value of a static or instance |
char |
getChar(Object obj) Gets the value of a static or instance field of type |
Annotation[] |
getDeclaredAnnotations() Returns annotations that are directly present on this element. 返回直接存在于此元素上的注释。 |
Class> |
getDeclaringClass() Returns the 返回表示声明此Field对象表示的字段的类或接口的Class对象。 |
double |
getDouble(Object obj) Gets the value of a static or instance field of type |
float |
getFloat(Object obj) Gets the value of a static or instance field of type |
Type |
getGenericType() Returns a |
int |
getInt(Object obj) Gets the value of a static or instance field of type |
long |
getLong(Object obj) Gets the value of a static or instance field of type |
int |
getModifiers() Returns the Java language modifiers for the field represented by this |
String |
getName() Returns the name of the field represented by this |
short |
getShort(Object obj) Gets the value of a static or instance field of type |
Class> |
getType() Returns a 返回一个Class对象,该对象标识此Field对象表示的字段的声明类型。 |
int |
hashCode() Returns a hashcode for this |
boolean |
isEnumConstant() Returns 如果此字段表示枚举类型的元素,则返回true;否则,返回true。 否则返回false。 |
boolean |
isSynthetic() Returns |
void |
set(Object obj, Object value) Sets the field represented by this |
void |
setBoolean(Object obj, boolean z) Sets the value of a field as a |
void |
setByte(Object obj, byte b) Sets the value of a field as a |
void |
setChar(Object obj, char c) Sets the value of a field as a |
void |
setDouble(Object obj, double d) Sets the value of a field as a |
void |
setFloat(Object obj, float f) Sets the value of a field as a |
void |
setInt(Object obj, int i) Sets the value of a field as an |
void |
setLong(Object obj, long l) Sets the value of a field as a |
void |
setShort(Object obj, short s) Sets the value of a field as a |
String |
toGenericString() Returns a string describing this |
String |
toString() Returns a string describing this |
public final class Method extends Executable
Modifier and Type | Method and Description |
---|---|
boolean |
equals(Object obj) Compares this |
AnnotatedType |
getAnnotatedReturnType() Returns an |
|
getAnnotation(Class 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 |
Object |
getDefaultValue() Returns the default value for the annotation member represented by this |
Class>[] |
getExceptionTypes() Returns an array of |
Type[] |
getGenericExceptionTypes() Returns an array of |
Type[] |
getGenericParameterTypes() Returns an array of |
Type |
getGenericReturnType() Returns a |
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 |
Annotation[][] |
getParameterAnnotations() Returns an array of arrays of |
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> |
getReturnType() Returns a |
TypeVariable |
getTypeParameters() Returns an array of |
int |
hashCode() Returns a hashcode for this |
Object |
invoke(Object obj, Object... args) Invokes the underlying method represented by this |
boolean |
isBridge() Returns |
boolean |
isDefault() Returns |
boolean |
isSynthetic() Returns |
boolean |
isVarArgs() Returns |
String |
toGenericString() Returns a string describing this |
String |
toString() Returns a string describing this |
public final class Constructorextends Executable
Modifier and Type | Method and Description |
---|---|
boolean |
equals(Object obj) Compares this |
AnnotatedType |
getAnnotatedReceiverType() Returns an |
AnnotatedType |
getAnnotatedReturnType() Returns an |
|
getAnnotation(Class 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>[] |
getExceptionTypes() Returns an array of |
Type[] |
getGenericExceptionTypes() Returns an array of |
Type[] |
getGenericParameterTypes() Returns an array of |
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 |
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 |
TypeVariable |
getTypeParameters() Returns an array of |
int |
hashCode() Returns a hashcode for this |
boolean |
isSynthetic() Returns |
boolean |
isVarArgs() Returns |
T |
newInstance(Object... initargs) Uses the constructor represented by this |
String |
toGenericString() Returns a string describing this |
String |
toString() Returns a string describing this |
public class Modifier extends Object
Modifier and Type | Field and Description |
---|---|
static int |
ABSTRACT The |
static int |
FINAL The |
static int |
INTERFACE The |
static int |
NATIVE The |
static int |
PRIVATE The |
static int |
PROTECTED The |
static int |
PUBLIC The |
static int |
STATIC The |
static int |
STRICT The |
static int |
SYNCHRONIZED The |
static int |
TRANSIENT The |
static int |
VOLATILE The |
示例代码
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 |
运行结果
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; |
public class AccessibleObject extends Object implements AnnotatedElement
作用如下
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.
简言之,就是可以设置权限,访问原本权限不足以访问的包,类,保护或私有的字段与方法
Modifier | Constructor and Description |
---|---|
protected |
AccessibleObject() Constructor: only used by the Java Virtual Machine. 构造函数:仅由Java虚拟机使用。 |
Modifier and Type | Method and Description |
---|---|
|
getAnnotation(Class 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. |
|
getAnnotationsByType(Class Returns annotations that are associated with this element. 返回与此元素关联的注释。 |
|
getDeclaredAnnotation(Class 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. |
|
getDeclaredAnnotationsByType(Class 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 获取此对象的可访问标志的值。 |
boolean |
isAnnotationPresent(Class extends Annotation> 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 |
void |
setAccessible(boolean flag) Set the |
setAccessible方法是AccessibleObject类中的一个方法,它是Field,Method和Constructor类的公共超类。这个特性是为调试,持久存储和相似机制提供的。
下面程序编写一个可供任意类使用的通用toString方法。
可以使用toString方法查看任意对象的内部信息。例如,下面这个调用:
1 2 3 |
ArrayList |
还可以使用通用的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 |
测试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 |
运行结果
使用反射编写泛型数组代码
下面程序显示两个扩展数组的方法。请注意,将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
public final class Array extends Object
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.
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 返回指定数组对象中索引组件的布尔值。 |
static byte |
getByte(Object array, int index) Returns the value of the indexed component in the specified array object, as a 以字节为单位返回指定数组对象中索引组件的值。 |
static char |
getChar(Object array, int index) Returns the value of the indexed component in the specified array object, as a |
static double |
getDouble(Object array, int index) Returns the value of the indexed component in the specified array object, as a |
static float |
getFloat(Object array, int index) Returns the value of the indexed component in the specified array object, as a |
static int |
getInt(Object array, int index) Returns the value of the indexed component in the specified array object, as an |
static int |
getLength(Object array) Returns the length of the specified array object, as an |
static long |
getLong(Object array, int index) Returns the value of the indexed component in the specified array object, as a |
static short |
getShort(Object array, int index) Returns the value of the indexed component in the specified array object, as a |
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 将指定数组对象的索引组件的值设置为指定的布尔值 |
static void |
setByte(Object array, int index, byte b) Sets the value of the indexed component of the specified array object to the specified 将指定数组对象的索引组件的值设置为指定的字节值。 |
static void |
setChar(Object array, int index, char c) Sets the value of the indexed component of the specified array object to the specified |
static void |
setDouble(Object array, int index, double d) Sets the value of the indexed component of the specified array object to the specified |
static void |
setFloat(Object array, int index, float f) Sets the value of the indexed component of the specified array object to the specified |
static void |
setInt(Object array, int index, int i) Sets the value of the indexed component of the specified array object to the specified |
static void |
setLong(Object array, int index, long l) Sets the value of the indexed component of the specified array object to the specified |
static void |
setShort(Object array, int index, short s) Sets the value of the indexed component of the specified array object to the specified |
调用任意方法
java.lang.reflect
public final class Method extends Executable
Modifier and Type | Method and Description | |
---|---|---|
boolean |
equals(Object obj) Compares this |
|
AnnotatedType |
getAnnotatedReturnType() Returns an |
|
|
getAnnotation(Class 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 |
|
Object |
getDefaultValue() Returns the default value for the annotation member represented by this |
|
Class>[] |
getExceptionTypes() Returns an array of |
|
Type[] |
getGenericExceptionTypes() Returns an array of |
|
Type[] |
getGenericParameterTypes() Returns an array of |
|
Type |
getGenericReturnType() Returns a |
|
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 |
|
Annotation[][] |
getParameterAnnotations() Returns an array of arrays of |
|
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> |
getReturnType() Returns a |
|
TypeVariable |
getTypeParameters() Returns an array of |
|
int |
hashCode() Returns a hashcode for this |
|
Object |
invoke(Object obj, Object... args) Invokes the underlying method represented by this 在具有指定参数的指定对象上调用由此方法对象表示的基础方法。 |
|
boolean |
isBridge() Returns |
|
boolean |
isDefault() Returns |
|
boolean |
isSynthetic() Returns 如果该可执行文件是合成结构,则返回true;否则返回false。 |
|
boolean |
isVarArgs() Returns 如果该可执行文件被声明为具有可变数量的参数,则返回true;否则返回false。 |
|
String |
toGenericString() Returns a string describing this 返回描述此方法的字符串,包括类型参数。 |
|
String |
|
|
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; } } |
运行结果