package cm.day6.reverberate;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
public class ReflectDemo {
/**
* @param args
*/
public static void main(String[] args)throws Exception{
Task task = new Task("abc","aac",99,'c');
System.out.print("当前值");
task.show();
/*
*Field修改String类型变量
*/
Field[] fields = task.getClass().getFields();
for(Field fie : fields){
System.out.println(fie.getName());
if(fie.getType() == String.class){
String value = (String)fie.get(task);
String newValue = value.replace("a", "x");
fie.set(task,newValue);
}
if(fie.getType() == char.class){
char vachar = fie.getChar(task);
vachar = 'x';
fie.setChar(task, vachar);
}
if(fie.getType() == int.class){
int i = fie.getInt(task);
int a = 999;
fie.setInt(task, a);
}
}
System.out.print("修改值");
task.show();
/*
* Method方法获取指定类方法
*/
//获得一个String类charAt(int)方法
Method method = String.class.getMethod("charAt",int.class);
String str = "abcde";
System.out.println(method.invoke(str, 2));
/*
* Constructor方法获取指定类构造方法
*/
Class ct = Class.forName("cm.day6.reverberate.Task");
//包名为:
Package p = ct.getPackage();
System.out.println("包名为:" + p);
//获取指定构造方法
Constructor c = ct.getDeclaredConstructor(String.class,String.class,int.class,char.class);
Integer a = (Integer)c.newInstance(new Task("avv","a",0,'x'));//newInstance()方法报错传入的参数不对
System.out.println(a.toString());
//System.out.println(ct);
}
}
class Task{
public int num;
public char nums;
public String demo1;
public String demo2;
Task(String demo1,String demo2,int num,char nums){
this.demo1 = demo1;
this.demo2 = demo2;
this.num = num;
this.nums = nums;
}
Task(){
this.num = num;
}
public void show(){
System.out.println("demo1:" + demo1 + "\tdemo2:" + demo2 + "\tnum:" + num + "\tnums:" + nums);
}
}
报错
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at cm.day6.reverberate.ReflectDemo.main(ReflectDemo.java:56)
谁说下newInstance()方法 谢谢
|