java高階反射之獲取欄位(三)
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);
}
}