通过反射获得对象的方法
准备工作:
有一个User类如下
package o1; /**
* Created by yesiming on 16-11-19.
*/
public class User {
private int id;
private String name // 无参构造方法
public User() {
System.out.println("new Instance() 1");
}
// 有参构造方法
public User(int id, String name) {
System.out.println(id + ":" + name + ":new Instance() 2");
}
// get set 省略
}
下面写得到User对象的几种方法:
package o1; import org.junit.Test; import java.io.File;
import java.lang.reflect.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL; /**
* Created by yesiming on 16-11-19.
*/
public class MainTest { @Test
public void getClazz() {
Class clazz = User.class; // 得到User的类描述
System.out.println(clazz.toString());
} @Test
public void getClazz1() {
Class clazz = User.class;
try {
Object obj = clazz.newInstance(); // 通过类描述的newInstance()方法可以得到该类的对象(内部会调用无参构造方法)
System.out.println(obj.toString());
} catch (Exception e) { } finally {
}
} @Test
public void getClazz2() {
Class clazz = User.class;
try {
// 通过类描述的getDeclaredConstructor(Class... clazz)方法得到对应的构造函数
Constructor constructor = clazz.getDeclaredConstructor(int.class, String.class);
// 通过对应的构造函数的newInstance(xxx, xxx)方法得到类对象
Object obj = constructor.newInstance(1, "iming"); // 通过
System.out.println(obj.toString());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} /**
* 通过getMethod(String methodName)得到方法描述符
* 通过方法描述符的invode(类描述符 xxx )方法,执行该方法
*/
@Test
public void getMethod() throws Exception {
Class clazz = User.class;
Constructor constructor = clazz.getDeclaredConstructor(int.class, String.class);
Object obj = constructor.newInstance(1, "yesiming");
Method m = clazz.getMethod("setName", String.class);
m.invoke(obj, "Haha"); Method m2 = clazz.getMethod("getName");
Object obj1 = m2.invoke(obj);
System.out.println(obj1.toString());
} /**
* 得到指定包名下所有的类
*/
@Test
public void getClasses() throws Exception {
Class clazz = User.class;
ClassLoader loader = clazz.getClassLoader();
// 1. 通过classloader载入包路径,得到url
URL url = loader.getResource("o1/o1_a");
URI uri = url.toURI();
// 2. 通过File获得uri下的所有文件
File file = new File(uri);
File[] files = file.listFiles();
for (File f : files) {
String fName = f.getName();
if (!fName.endsWith(".class")) {
continue;
}
fName = fName.substring(0, fName.length() - 6);
String perfix = "o1.o1_a.";
String allName = perfix + fName;
// 3. 通过反射加载类
clazz = Class.forName(allName);
System.out.println(clazz);
}
} }