package com.jk.fs;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
*
* @author sx123
*
*/
public class ReflectzDemo {
public static void main(String[] args) throws Exception {
//getFieldDemo();
getMethodDemo_3();
}
/**
* 反射机制(获取Class中的字段)
* @throws ClassNotFoundException
* @throws NoSuchFieldException
* @throws Exception
*/
public static void getFieldDemo() throws ClassNotFoundException, NoSuchFieldException, Exception {
Class clazz = Class.forName("com.jk.bean.Person");
//Field field = clazz.getField("age");//只能获取公有的字段
Field field =clazz.getDeclaredField("age");//只获取本类的所有的字段
//对私有字段的访问取消权限检查 暴力访问
field.setAccessible(true);
Object obj = clazz.newInstance();
field.set(obj, 88);
Object o = field.get(obj);
System.out.println(o);
}
/**
* 反射机制(获取Class中的方法)
* 获取指定Class中的公共函数
* @throws Exception
*/
public static void getMethodDemo() throws Exception {
Class clazz = Class.forName("com.jk.bean.Person");
Method[] methods = clazz.getMethods();//获取的都是共有方法(public)
methods = clazz.getDeclaredMethods();//只获取本类中所有方法,包含私有
for(Method method:methods) {
System.out.println(method);
}
}
public static void getMethodDemo_2() throws Exception {
Class clazz = Class.forName("com.jk.bean.Person");
Method method = clazz.getMethod("show", null);//获取空参数一般方法
// Object obj = clazz.newInstance();
Constructor constructor = clazz.getConstructor(String.class,int.class);
Object obj = constructor.newInstance("小明",32);
method.invoke(obj, null);
}
public static void getMethodDemo_3() throws Exception{
Class clazz = Class.forName("com.jk.bean.Person");
Method method = clazz.getMethod("paramMethod", String.class,int.class);//获取空参数一般方法
Object obj = clazz.newInstance();
method.invoke(obj, "小强",43);
}
}