反射修改私有成员变量
public class Homework01 {
public static void main ( String [ ] args) throws IllegalAccessException , InstantiationException , NoSuchFieldException , NoSuchMethodException , InvocationTargetException {
Class < PrivateTest > privateTestClass = PrivateTest . class ;
PrivateTest privateTestObj = privateTestClass. newInstance ( ) ;
Field name = privateTestClass. getDeclaredField ( "name" ) ;
name. setAccessible ( true ) ;
name. set ( privateTestObj, "天龙八部" ) ;
Method getName = privateTestClass. getMethod ( "getName" ) ;
Object invoke = getName. invoke ( privateTestObj) ;
System . out. println ( "name属性值=" + invoke) ;
}
}
class PrivateTest {
private String name = "hellokitty" ;
public String getName ( ) {
return name;
}
}
反射和File
public class Homework02 {
public static void main ( String [ ] args) throws ClassNotFoundException , NoSuchMethodException , IllegalAccessException , InvocationTargetException , InstantiationException {
Class < ? > fileCls = Class . forName ( "java.io.File" ) ;
Constructor < ? > [ ] declaredConstructors = fileCls. getDeclaredConstructors ( ) ;
for ( Constructor < ? > declaredConstructor : declaredConstructors) {
System . out. println ( "File构造器=" + declaredConstructor) ;
}
Constructor < ? > declaredConstructor = fileCls. getDeclaredConstructor ( String . class ) ;
String fileAllPath = "e:\\mynew.txt" ;
Object file = declaredConstructor. newInstance ( fileAllPath) ;
Method createNewFile = fileCls. getMethod ( "createNewFile" ) ;
createNewFile. invoke ( file) ;
System . out. println ( file. getClass ( ) ) ;
System . out. println ( "创建文件成功" + fileAllPath) ;
}
}