List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.zhuangjy.dao.ReflectionUtil.java
/** * , private/protected.//from ww w. j a v a2s.c o m */ public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes, final Object[] parameters) throws InvocationTargetException, IllegalAccessException { Method method = getDeclaredMethod(object, methodName, parameterTypes); if (method == null) throw new IllegalArgumentException( "Could not find method [" + methodName + "] on target [" + object + "]"); method.setAccessible(true); return method.invoke(object, parameters); }
From source file:com.autobizlogic.abl.util.BeanUtil.java
private static void setValueWithMethod(Method setterMethod, Object bean, Object value) { try {// ww w . ja va2 s . c o m setterMethod.setAccessible(true); setterMethod.invoke(bean, value); } catch (Exception ex) { throw new RuntimeException("Unable to use set method " + setterMethod.getName() + " on instance of " + bean.getClass().getName(), ex); } }
From source file:org.caratarse.auth.model.util.BeanUtils.java
/** * Copy the not-null property values of the given source bean into the given target bean. * <p>//from w w w .j av a2s .c o m * Note: The source and target classes do not have to match or even be derived from each other, * as long as the properties match. Any bean properties that the source bean exposes but the * target bean does not will silently be ignored. * * @param source the source bean * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void copyNotNullProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = org.springframework.beans.BeanUtils.getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = org.springframework.beans.BeanUtils .getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (value == null) { continue; } if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
From source file:net.drgnome.virtualpack.util.Util.java
public static boolean loadJar(File file) { ClassLoader loader = _plugin.getClass().getClassLoader(); if (loader instanceof URLClassLoader) { try { URLClassLoader cl = (URLClassLoader) loader; Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m.setAccessible(true); m.invoke(cl, file.toURI().toURL()); } catch (Exception e) { warn();// w w w .ja v a 2s .c om e.printStackTrace(); return false; } } else { warn(); _log.severe("[VirtualPack] PluginClassLoader not URLClassLoader!"); return false; } return true; }
From source file:Main.java
public static Method findMethodByNameAndReturnType(Class<?> targetObject, String methodName, String returnType, Class<?>... params) { for (Method method : targetObject.getDeclaredMethods()) { if (method.getReturnType().getName().equals(returnType) && method.getName().equals(methodName)) { Class[] parameterTypes = method.getParameterTypes(); if (params.length != parameterTypes.length) { continue; }/*from w w w. jav a 2s . co m*/ for (int i = 0; i < params.length; i++) { if (params[i] != parameterTypes[i]) { break; } } method.setAccessible(true); return method; } } throw new NoSuchMethodError(); }
From source file:Main.java
/** * Gets a method and forces it to be accessible, even if it is not. * * @param clazz The class from which the method will be got. * @param methodName The name of the method. * @param parameterTypes The parameter types that the method must match. * @return The method, if it is found./*ww w . j a v a 2s .c o m*/ * @since 2.0.7 */ public static Method getForcedAccessibleMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { Method method; try { method = clazz.getMethod(methodName, parameterTypes); } catch (SecurityException e) { throw new RuntimeException("Cannot access method '" + methodName + "' in class '" + clazz.getName() + "' for security reasons", e); } catch (NoSuchMethodException e) { throw new RuntimeException( "The method '" + methodName + "' in class '" + clazz.getName() + "' does not exist", e); } if (!method.isAccessible()) { method.setAccessible(true); } return method; }
From source file:com.mgmtp.jfunk.web.util.WebElementFinder.java
private static void checkElementState(final WebElement element, final boolean expression, final String msgTemplate) { if (!expression) { WebElement underlyingElement;/*from w ww . jav a2 s . c om*/ try { Method m = element.getClass().getMethod("getWrappedElement"); m.setAccessible(true); underlyingElement = (WebElement) m.invoke(element); } catch (Exception ex) { underlyingElement = element; } throw new WebElementException(String.format(msgTemplate, underlyingElement)); } }
From source file:com.ms.commons.test.common.ReflectUtil.java
public static Object invokeMethod(Class<?> clazz, Object object, String methodName, Class<?>[] parameterTypes, Object[] parameters) {/*from w ww .j a v a 2s. c om*/ Method method = getDeclaredMethod(clazz, methodName, parameterTypes); if (method == null) { throw new RuntimeException("Method `" + methodName + "` not found in class `" + clazz.getName() + "`."); } if (!method.isAccessible()) { method.setAccessible(true); } try { return method.invoke(object, parameters); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
From source file:com.linkedin.pinot.common.utils.MmapUtils.java
/** * Unloads a byte buffer from memory/*from w w w. j av a 2s. c o m*/ * * @param buffer The buffer to unload, can be null */ public static void unloadByteBuffer(Buffer buffer) { if (null == buffer) return; // Non direct byte buffers do not require any special handling, since they're on heap if (!buffer.isDirect()) return; // Remove usage from direct byte buffer usage final int bufferSize = buffer.capacity(); final AllocationContext bufferContext = BUFFER_TO_CONTEXT_MAP.get(buffer); // A DirectByteBuffer can be cleaned up by doing buffer.cleaner().clean(), but this is not a public API. This is // probably not portable between JVMs. try { Method cleanerMethod = buffer.getClass().getMethod("cleaner"); Method cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean"); cleanerMethod.setAccessible(true); cleanMethod.setAccessible(true); // buffer.cleaner().clean() Object cleaner = cleanerMethod.invoke(buffer); if (cleaner != null) { cleanMethod.invoke(cleaner); if (bufferContext != null) { switch (bufferContext.allocationType) { case DIRECT_BYTE_BUFFER: DIRECT_BYTE_BUFFER_USAGE.addAndGet(-bufferSize); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Releasing byte buffer of size {} with context {}, allocation after operation {}", bufferSize, bufferContext, getTrackedAllocationStatus()); } break; case MMAP: MMAP_BUFFER_USAGE.addAndGet(-bufferSize); MMAP_BUFFER_COUNT.decrementAndGet(); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Unmapping byte buffer of size {} with context {}, allocation after operation {}", bufferSize, bufferContext, getTrackedAllocationStatus()); } break; } BUFFER_TO_CONTEXT_MAP.remove(buffer); } else { LOGGER.warn( "Attempted to release byte buffer of size {} with no context, no deallocation performed.", bufferSize); if (LOGGER.isDebugEnabled()) { List<String> matchingAllocationContexts = new ArrayList<>(); synchronized (BUFFER_TO_CONTEXT_MAP) { clearSynchronizedMapEntrySetCache(); for (Map.Entry<ByteBuffer, AllocationContext> byteBufferAllocationContextEntry : BUFFER_TO_CONTEXT_MAP .entrySet()) { if (byteBufferAllocationContextEntry.getKey().capacity() == bufferSize) { matchingAllocationContexts .add(byteBufferAllocationContextEntry.getValue().toString()); } } // Clear the entry set cache afterwards so that we don't hang on to stale entries clearSynchronizedMapEntrySetCache(); } LOGGER.debug("Contexts with a size of {}: {}", bufferSize, matchingAllocationContexts); LOGGER.debug("Called by: {}", Utils.getCallingMethodDetails()); } } } } catch (Exception e) { LOGGER.warn("Caught (ignored) exception while unloading byte buffer", e); } }
From source file:org.zht.framework.util.ZBeanUtil.java
private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); }/* ww w. j a v a 2 s . c o m*/ actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (ignorNull != null && ignorNull) { if (value != null && (!"[]".equals(value.toString()))) {// ? if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } else { if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }