接Java反射研究(1)
九、调用特定方法
Method m = c1.getMethod("funcname",Class<?>...c); //funcname表示调用方法的名称,c表示参数的Class对象
例如:Method m = c1.getMethod("fun",String.class,int.class); 表示调用fun(String,int);函数
Object obj = m.invoke(c1.newInstance(),"xiazdong",20); //如果有返回值,则invoke函数返回;
注:如果是调用静态的方法,则不需要设置对象;
Object obj = m.invoke(null,"xiazdong");
注:如果参数中有数组,比如 public static void main(String[]args);
则
Method m = c1.getMethod("main",String[].class);
m.invoke(null,(Object)new String[]{"aa","bb"});是对的;
m.invoke(null,new String[]{"aa","bb"}); 会调用 main(String,String);函数;
十、调用特定属性
Field f = c1.getDeclaredField("name"); //返回name属性
f.setAccessible(true); //私有属性可见
String name = (String)f.get(Object obj); //返回obj对象的name属性的值
f.set(Object obj,String n); //设置obj对象的name属性为n值;
十一、操作数组
int tmp[] = {1,2,3};
Class<?> c = tmp.getClass().getComponentType();
Array.getLength(tmp); //tmp数组的长度
c.getName(); //获得数组类型名称
Array.get(Object obj,int index); //获得obj数组的index索引的数值
Array.set(Object obj,int index,VALUE); //设置obj数组的index索引的数值为value;
Object obj = Array.newInstance(c,length); //c为数组的类型,length为数组的长度;obj为返回的数组对象;
示例:
import java.lang.reflect.*;
public class GetMethodDemo01{
public static void main(String args[])throws Exception{
Class<?> c1 = Class.forName("Person");
Method m = c1.getMethod("sayHello");
m.invoke(c1.newInstance());
Method m2 = c1.getMethod("sayHello2",String.class,int.class);
String str = (String)m2.invoke(c1.newInstance(),"xiazdong",123);
System.out.println(str);
Field nameField = c1.getDeclaredField("name");
Field ageField = c1.getDeclaredField("age");
nameField.setAccessible(true);
ageField.setAccessible(true);
Person obj = (Person)c1.newInstance();
obj.setName("xzdong");
obj.setAge(12);
System.out.println(nameField.get(obj));
System.out.println(ageField.get(obj));
Method setName = c1.getMethod("setName",String.class);
setName.invoke(obj,"changed");
Method getName = c1.getMethod("getName");
System.out.println(getName.invoke(obj));
int tmp[] = {1,2,3};
Class<?> c3 = tmp.getClass().getComponentType();
System.out.println(c3.getName());
System.out.println("第一个数:"+Array.get(tmp,0));
Array.set(tmp,0,5);
System.out.println("第一个数:"+Array.get(tmp,0));
Object arr = Array.newInstance(c3,5);
System.arraycopy(tmp,0,arr,0,Array.getLength(tmp));
System.out.println(Array.get(arr,2));
System.out.println(Array.get(arr,3));
}
}
import java.lang.reflect.*;
interface China{
public static final String NAME = "CHINA";
public int AGE = 60;
public void sayHello();
public String sayHello2(String name,int age);
}
class Person implements China{
private String name;
private int age;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public void sayHello(){
System.out.println(NAME+" "+AGE);
}
public String sayHello2(String name,int age){
return name+" "+age;
}
}