getDeclaredFields()应用
生活随笔
收集整理的這篇文章主要介紹了
getDeclaredFields()应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
調用private類型的變量及方法
BeanUtils.java
package com.lmb.util;import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils;import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;/*** 擴展Apache Commons BeanUtils, 提供一些反射方面缺失功能的封裝.*/ public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {protected static final Log logger = LogFactory.getLog(BeanUtils.class);private BeanUtils() {}/*** 循環向上轉型,獲取對象的DeclaredField.** @throws NoSuchFieldException 如果沒有該Field時拋出.*/public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException {Assert.notNull(object);Assert.hasText(propertyName);return getDeclaredField(object.getClass(), propertyName);}/*** 循環向上轉型,獲取對象的DeclaredField.** @throws NoSuchFieldException 如果沒有該Field時拋出.*/public static Field getDeclaredField(Class clazz, String propertyName) throws NoSuchFieldException {Assert.notNull(clazz);Assert.hasText(propertyName);for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {try {return superClass.getDeclaredField(propertyName);} catch (NoSuchFieldException e) {// Field不在當前類定義,繼續向上轉型 }}throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + propertyName);}/*** 暴力獲取對象變量值,忽略private,protected修飾符的限制.** @throws NoSuchFieldException 如果沒有該Field時拋出.*/public static Object forceGetProperty(Object object, String propertyName) throws NoSuchFieldException {Assert.notNull(object);Assert.hasText(propertyName);Field field = getDeclaredField(object, propertyName);boolean accessible = field.isAccessible();field.setAccessible(true);Object result = null;try {result = field.get(object);} catch (IllegalAccessException e) {logger.info("error wont' happen");}field.setAccessible(accessible);return result;}/*** 暴力設置對象變量值,忽略private,protected修飾符的限制.** @throws NoSuchFieldException 如果沒有該Field時拋出.*/public static void forceSetProperty(Object object, String propertyName, Object newValue)throws NoSuchFieldException {Assert.notNull(object);Assert.hasText(propertyName);Field field = getDeclaredField(object, propertyName);boolean accessible = field.isAccessible();field.setAccessible(true);try {field.set(object, newValue);} catch (IllegalAccessException e) {logger.info("Error won't happen");}field.setAccessible(accessible);}/*** 暴力調用對象函數,忽略private,protected修飾符的限制.** @throws NoSuchMethodException 如果沒有該Method時拋出.*/@SuppressWarnings("unchecked")public static Object invokePrivateMethod(Object object, String methodName, Object... params)throws NoSuchMethodException {Assert.notNull(object);//object對象不為空,否則拋出異常Assert.hasText(methodName);//methodName 不能為 null 且必須至少包含一個非空格的字符,否則拋出異常Class[] types = new Class[params.length];for (int i = 0; i < params.length; i++) {types[i] = params[i].getClass();}Class clazz = object.getClass();Method method = null;for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {try {//獲取superClass類自身聲明的符合入參要求的所有方法,包含public、protected和private方法method = superClass.getDeclaredMethod(methodName, types);break;} catch (NoSuchMethodException e) {// 方法不在當前類定義,繼續向上轉型}}if (method == null)throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);boolean accessible = method.isAccessible();//獲取方法的可用性情況method.setAccessible(true);Object result = null;try {result = method.invoke(object, params);//調用該方法} catch (Exception e) {ReflectionUtils.handleReflectionException(e);}method.setAccessible(accessible);//還原方法的可用性情況return result;}/*** 按Filed的類型取得Field列表.*/public static List<Field> getFieldsByType(Object object, Class type) {List<Field> list = new ArrayList<Field>();Field[] fields = object.getClass().getDeclaredFields();for (Field field : fields) {if (field.getType().isAssignableFrom(type)) {list.add(field);}}return list;}/*** 按FiledName獲得Field的類型.*/public static Class getPropertyType(Class type, String name) throws NoSuchFieldException {return getDeclaredField(type, name).getType();}/*** 獲得field的getter函數名稱.*/public static String getGetterName(Class type, String fieldName) {Assert.notNull(type, "Type required");Assert.hasText(fieldName, "FieldName required");if (type.getName().equals("boolean")) {return "is" + StringUtils.capitalize(fieldName);} else {return "get" + StringUtils.capitalize(fieldName);}}/*** 獲得field的getter函數,如果找不到該方法,返回null.*/public static Method getGetterMethod(Class type, String fieldName) {try {return type.getMethod(getGetterName(type, fieldName));} catch (NoSuchMethodException e) {logger.error(e.getMessage(), e);}return null;} }實現java反射調用別的類
寫一個類Simple.java
public class Simple {private void displayMessage(String strMsg) {System.out.println("message is:" + strMsg);} }反射調用
import java.lang.reflect.*;public class Test {/*** @param args* @throws ClassNotFoundException* @throws NoSuchMethodException* @throws SecurityException* @throws IllegalAccessException* @throws InstantiationException* @throws InvocationTargetException* @throws IllegalArgumentException*/public static void main(String[] args) throws ClassNotFoundException,SecurityException, NoSuchMethodException, InstantiationException,IllegalAccessException, IllegalArgumentException,InvocationTargetException {Class simpleClass = Class.forName("Simple");Object simpelObject = simpleClass.newInstance();//獲取simple類的實例對象Class[] args1 = new Class[1];args1[0] = String.class;Method simpleMethod = simpleClass.getDeclaredMethod("displayMessage",args1); //得到方法名為displayMessage,參數類型為args1內的參數類型的方法(private public protected)simpleMethod.setAccessible(true);//設置方法可用String[] argments = new String[1];argments[0] = "Hello,world";simpleMethod.invoke(simpelObject, argments);//調用該方法} }總結
以上是生活随笔為你收集整理的getDeclaredFields()应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: InetAddress.getLocal
- 下一篇: Ajax系统学习总结