getDeclaredFields()应用
来源:互联网 发布:喊麦声卡软件 编辑:程序博客网 时间:2024/05/16 11:23
调用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);//调用该方法 }}
2 0
- getDeclaredFields()应用
- getFields()和getDeclaredFields()
- getFields()与getDeclaredFields()区别
- getFields()和getDeclaredFields()
- getFields()和getDeclaredFields()
- getFields()和getDeclaredFields()
- getFields()和getDeclaredFields()区别
- getFields()和getDeclaredFields()
- getFields()与getDeclaredFields()区别
- getFields()和getDeclaredFields()
- Java反射 getFields()和getDeclaredFields()
- getFields()和getDeclaredFields()的区别
- getDeclaredFields()和getFields()
- Java反射 getFields()和getDeclaredFields()的区别
- Java反射 getFields()和getDeclaredFields()的区别
- Java反射 getFields()和getDeclaredFields()的区
- Java反射 getFields()和getDeclaredFields()的区别
- java Class.getFields与getDeclaredFields区别
- Android TTS
- NYOJ 222 整数中的1 (二进制位运算,找规律)
- WebBasic04-CSS
- wpf重绘窗体
- 约瑟夫环问题【数组】
- getDeclaredFields()应用
- 【BZOJ3158】千钧一发,网络流之最大权闭合子图
- JedisConnectionException: java.net.ConnectException: Connection refused: connect
- 取数字
- Android TextureView 和 SurfaceView 对比浅析
- 设备管理器
- 我的第一篇博客
- 203. Remove Linked List Elements
- Contiki在CC2530上的内核移植