通过一个类,创造这个类的实例
通过一个类,查找这个类的方法
通过一个类,查找这个类的属性
package cn.itcast.jdbc;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args)throws Exception{
Class clazz = User.class;
Object obj = create(clazz);
System.out.println(obj);
invoke1(obj,"getId"); //作用?
field(clazz); //输出 id name birthday money 这些类的属性
}
/*通过一个类,创造出一个实例*/
static Object create(Class clazz)throws Exception{
Constructor con = clazz.getConstructor(String.class);
Object obj = con.newInstance("test name");
return obj;
}
/*通过类的方法名,调用这个类的方法*/
static void invoke1(Object obj, String methodName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
//Method 提供关于类或接口上单独某个方法(以及如何访问该方法)的信息
Method[] ms = obj.getClass().getDeclaredMethods(); //包括私有方法,不包括公共方法
ms = obj.getClass().getMethods(); //不包括私有方法,包括公共方法
for(Method m : ms){
System.out.println(m.getName());
if(methodName.equals(m.getName())){
m.invoke(obj, null);
}
}
Method m = obj.getClass().getMethod(methodName,null);
m.invoke(obj, null);
}
//查找某个类的属性
static void field(Class clazz) throws Exception{
Field[] fs = clazz.getDeclaredFields();
//fs = clazz.getFields();
for(Field f : fs){
System.out.println(f.getName());
}
}
//?
static void annon(Class clazz) throws Exception{
Annotation[] as = clazz.getAnnotations();
}
}