assignfielddemo.java
来自「金旭亮的java教案」· Java 代码 · 共 42 行
JAVA
42 行
import java.lang.reflect.Field;
class TestField {
public int testInt;
public String testString;
public String toString() {
return testInt + ":" + testString;
}
}
public class AssignFieldDemo {
public static void main(String[] args) {
try {
Class c = Class.forName("TestField");
Object targetObj = c.newInstance();
Field testInt = c.getField("testInt");
testInt.setInt(targetObj, 99);
Field testString = c.getField("testString");
testString.set(targetObj, "jxl");
System.out.println(targetObj);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("没有指定类");
} catch (ClassNotFoundException e) {
System.out.println("找不到指定的类");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
System.out.println("找不到指定的域成员");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?