简介
获取class对象的API
Class < Student > clazz = Student . class ;
System . out. println ( clazz. getName ( ) ) ;
Class < ? > clazz2 = null ;
try {
clazz2 = Class . forName ( "com.reflect.Student" ) ;
System . out. println ( clazz2. getName ( ) ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
}
Class < ? > clazz3 = new Student ( ) . getClass ( ) ;
System . out. println ( clazz3. getName ( ) ) ;
获取构造器
获取构造器对象
Student student = new Student ( ) ;
Class clazz = student. getClass ( ) ;
Constructor [ ] constructors = clazz. getConstructors ( ) ;
System . out. println ( "只有public的构造方法" ) ;
for ( Constructor < ? > constructor : constructors) {
System . out. println ( constructor) ;
}
Constructor [ ] declaredConstructors = clazz. getDeclaredConstructors ( ) ;
System . out. println ( "包括private的构造方法" ) ;
for ( Constructor < ? > declaredConstructor : declaredConstructors) {
System . out. println ( declaredConstructor) ;
}
try {
Constructor constructor = clazz. getConstructor ( String . class , int . class ) ;
System . out. println ( "获取指定的构造方法" ) ;
System . out. println ( constructor) ;
} catch ( NoSuchMethodException e) {
e. printStackTrace ( ) ;
}
try {
Constructor < ? > declaredConstructor = clazz. getDeclaredConstructor ( String . class ) ;
System . out. println ( "获取指定的构造方法" ) ;
System . out. println ( declaredConstructor) ;
} catch ( NoSuchMethodException e) {
e. printStackTrace ( ) ;
}
使用构造器对象
Class clazz = Student . class ;
Constructor < Student > constructor = clazz. getConstructor ( String . class , int . class ) ;
Student newInstance = constructor. newInstance ( "张三" , 18 ) ;
System . out. println ( newInstance) ;
私有的构造器方法是不能直接被外部访问的,即使你拿到了也没用 除非你使用暴力反射
Constructor < Student > declaredConstructor = clazz. getDeclaredConstructor ( String . class ) ;
declaredConstructor. setAccessible ( true ) ;
Student privateStudent = declaredConstructor. newInstance ( "张三" ) ;
System . out. println ( privateStudent) ;