class TestDemo {
public static void main(String[] args)throws Exception {
//构造方法 constructor
String str = new String(new StringBuilder("abc"));
Constructor constructor = str.getClass().getConstructor(StringBuilder.class);
String str1 = (String)constructor.newInstance(new StringBuilder("abd"));
System.out.println(str+"..."+str1);
//Field类练习
TestDemo1 td = new TestDemo1(3,5);
Field fx = td.getClass().getField("x");
System.out.println(fx.get(td));
Field fy = td.getClass().getDeclaredField("y");
fy.setAccessible(true);
System.out.println(fy.get(td));
Field[] fields = td.getClass().getFields();
for (Field field : fields){
if (field.getType() == String.class){
String oldValue = (String)field.get(td);
String newValue = oldValue.replace('b', 'a');
field.set(td,newValue);
}
}
System.out.println(td);
//Method类练习1:
Method charAtMethod=String.class.getMethod("charAt", int.class);
System.out.println(charAtMethod.invoke(str, 2));
//练习2:
String classStartingName = args[0];
Method mainMethod = Class.forName(classStartingName).getMethod("main", String[].class);
mainMethod.invoke(null, (Object)new String[]{"111","222","333"});
}
}
class TestDemo1{
public int x ;
private int y;
public String str1 = "basketball";
public String str2 = "babay";
public String str3 = "but";
public TestDemo1(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString(){
return str1+":"+str2+":"+str3;
}
}
class MethodTestDemo1{
public static void main(String[] args) {
for (String str : args){
System.out.println(str);
}
}
} |
|