List of usage examples for java.lang.reflect Method isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:javadz.beanutils.MethodUtils.java
/** * Try to make the method accessible//from www . java 2s . c om * @param method The source arguments */ private static void setMethodAccessible(Method method) { try { // // XXX Default access superclass workaround // // When a public class has a default access superclass // with public methods, these methods are accessible. // Calling them from compiled code works fine. // // Unfortunately, using reflection to invoke these methods // seems to (wrongly) to prevent access even when the method // modifer is public. // // The following workaround solves the problem but will only // work from sufficiently privilages code. // // Better workarounds would be greatfully accepted. // if (!method.isAccessible()) { method.setAccessible(true); } } catch (SecurityException se) { // log but continue just in case the method.invoke works anyway Log log = LogFactory.getLog(MethodUtils.class); if (!loggedAccessibleWarning) { boolean vulnerableJVM = false; try { String specVersion = System.getProperty("java.specification.version"); if (specVersion.charAt(0) == '1' && (specVersion.charAt(2) == '0' || specVersion.charAt(2) == '1' || specVersion.charAt(2) == '2' || specVersion.charAt(2) == '3')) { vulnerableJVM = true; } } catch (SecurityException e) { // don't know - so display warning vulnerableJVM = true; } if (vulnerableJVM) { log.warn("Current Security Manager restricts use of workarounds for reflection bugs " + " in pre-1.4 JVMs."); } loggedAccessibleWarning = true; } log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se); } }
From source file:com.haulmont.cuba.core.sys.MetadataImpl.java
protected void invokePostConstructMethods(Entity entity) throws InvocationTargetException, IllegalAccessException { List<Method> postConstructMethods = new ArrayList<>(4); List<String> methodNames = new ArrayList<>(4); Class clazz = entity.getClass(); while (clazz != Object.class) { Method[] classMethods = clazz.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(PostConstruct.class) && !methodNames.contains(method.getName())) { postConstructMethods.add(method); methodNames.add(method.getName()); }/*www . j a va 2 s . c o m*/ } clazz = clazz.getSuperclass(); } ListIterator<Method> iterator = postConstructMethods.listIterator(postConstructMethods.size()); while (iterator.hasPrevious()) { Method method = iterator.previous(); if (!method.isAccessible()) { method.setAccessible(true); } method.invoke(entity); } }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * //from w w w.ja v a2 s . c om * @param obj * @return */ public Object extractId(Object obj) { if (entityIdField == null) return null; if (!entityIdField.isAccessible()) entityIdField.setAccessible(true); try { return entityIdField.get(obj); } catch (IllegalAccessException iae) { try { Method idGetter = getGetter(entityIdField); if (!idGetter.isAccessible()) idGetter.setAccessible(true); if (!idGetter.isAccessible()) return null; return idGetter.invoke(obj); } catch (NoSuchMethodException nsme) { log.error(nsme); } catch (IllegalAccessException ia) { log.error(ia); } catch (InvocationTargetException ite) { log.error(ite); } } return null; }
From source file:eu.qualityontime.commons.MethodUtils.java
/** * Try to make the method accessible/*from w w w.j av a2 s.co m*/ * * @param method * The source arguments */ private static void setMethodAccessible(final Method method) { try { // // XXX Default access superclass workaround // // When a public class has a default access superclass // with public methods, these methods are accessible. // Calling them from compiled code works fine. // // Unfortunately, using reflection to invoke these methods // seems to (wrongly) to prevent access even when the method // modifer is public. // // The following workaround solves the problem but will only // work from sufficiently privilages code. // // Better workarounds would be greatfully accepted. // if (!method.isAccessible()) { method.setAccessible(true); } } catch (final SecurityException se) { // log but continue just in case the method.invoke works anyway final Log log = LogFactory.getLog(MethodUtils.class); if (!loggedAccessibleWarning) { boolean vulnerableJVM = false; try { final String specVersion = System.getProperty("java.specification.version"); if (specVersion.charAt(0) == '1' && (specVersion.charAt(2) == '0' || specVersion.charAt(2) == '1' || specVersion.charAt(2) == '2' || specVersion.charAt(2) == '3')) { vulnerableJVM = true; } } catch (final SecurityException e) { // don't know - so display warning vulnerableJVM = true; } if (vulnerableJVM) { log.warn("Current Security Manager restricts use of workarounds for reflection bugs " + " in pre-1.4 JVMs."); } loggedAccessibleWarning = true; } log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se); } }
From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java
private void performMethodInjection(final Object instance, final Class authorizerClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (final Method method : authorizerClass.getMethods()) { if (method.isAnnotationPresent(AuthorizerContext.class)) { // make the method accessible final boolean isAccessible = method.isAccessible(); method.setAccessible(true);//from w w w . j av a2 s. c o m try { final Class<?>[] argumentTypes = method.getParameterTypes(); // look for setters (single argument) if (argumentTypes.length == 1) { final Class<?> argumentType = argumentTypes[0]; // look for well known types if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) { // nifi properties injection method.invoke(instance, properties); } } } finally { method.setAccessible(isAccessible); } } } final Class parentClass = authorizerClass.getSuperclass(); if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) { performMethodInjection(instance, parentClass); } }
From source file:org.codehaus.groovy.grails.orm.hibernate.proxy.GroovyAwareJavassistLazyInitializer.java
public Object invoke(final Object proxy, final Method thisMethod, final Method proceed, final Object[] args) throws Throwable { Object result = groovyObjectMethodHandler.handleInvocation(proxy, thisMethod, args); if (groovyObjectMethodHandler.wasHandled(result)) { return result; }//from ww w . java 2 s. c o m if (constructed) { try { result = invoke(thisMethod, args, proxy); } catch (Throwable t) { throw new Exception(t.getCause()); } if (result == INVOKE_IMPLEMENTATION) { Object target = getImplementation(); final Object returnValue; try { if (ReflectHelper.isPublic(persistentClass, thisMethod)) { if (!thisMethod.getDeclaringClass().isInstance(target)) { throw new ClassCastException(target.getClass().getName()); } returnValue = thisMethod.invoke(target, args); } else { if (!thisMethod.isAccessible()) { thisMethod.setAccessible(true); } returnValue = thisMethod.invoke(target, args); } return returnValue == target ? proxy : returnValue; } catch (InvocationTargetException ite) { throw ite.getTargetException(); } } return result; } // while constructor is running if (thisMethod.getName().equals("getHibernateLazyInitializer")) { return this; } return proceed.invoke(proxy, args); }
From source file:org.bremersee.comparator.ObjectComparatorImpl.java
@Override public int compare(Object o1, Object o2) { final boolean asc = getComparatorItem() != null ? getComparatorItem().isAsc() : true; final boolean ignoreCase = getComparatorItem() != null ? getComparatorItem().isIgnoreCase() : true; final boolean nullIsFirst = getComparatorItem() != null ? getComparatorItem().isNullIsFirst() : false; if (o1 == null && o2 == null) { return 0; }/* w ww. ja va2 s . co m*/ if (o1 == null && o2 != null) { if (asc) { return nullIsFirst ? -1 : 1; } else { return nullIsFirst ? 1 : -1; } } if (o1 != null && o2 == null) { if (asc) { return nullIsFirst ? 1 : -1; } else { return nullIsFirst ? -1 : 1; } } if (getComparatorItem() == null || StringUtils.isBlank(getComparatorItem().getField())) { if (asc && o1 instanceof Comparable) { if (ignoreCase && o1 instanceof String && o2 instanceof String) { return ((String) o1).compareToIgnoreCase((String) o2); } return ((Comparable) o1).compareTo(o2); } else if (!asc && o2 instanceof Comparable) { if (ignoreCase && o1 instanceof String && o2 instanceof String) { return ((String) o2).compareToIgnoreCase((String) o1); } return ((Comparable) o2).compareTo(o1); } else { return 0; } } Object v1 = o1; Object v2 = o2; // supports fields like: fieldName1.fieldName2.fieldName3 String[] fieldNames = getComparatorItem().getField().split(Pattern.quote(".")); for (String fieldName : fieldNames) { if (StringUtils.isNotBlank(fieldName) && v1 != null && v2 != null) { Field f1 = findField(v1.getClass(), fieldName.trim()); Field f2 = findField(v2.getClass(), fieldName.trim()); if (f1 != null && f2 != null) { if (!f1.isAccessible()) { f1.setAccessible(true); } if (!f2.isAccessible()) { f2.setAccessible(true); } try { v1 = f1.get(v1); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { throw new ObjectComparatorException(e); } try { v2 = f2.get(v2); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { throw new ObjectComparatorException(e); } } else { Method m1 = null; Method m2 = null; String[] methodNames = getPossibleMethodNames(fieldName.trim()); for (String methodName : methodNames) { m1 = findMethod(v1.getClass(), methodName); m2 = findMethod(v2.getClass(), methodName); if (m1 != null && m2 != null) { break; } } if (m1 == null) { return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(v1, v2); } if (m2 == null) { return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(v1, v2); } if (!m1.isAccessible()) { m1.setAccessible(true); } if (!m2.isAccessible()) { m2.setAccessible(true); } try { v1 = m1.invoke(v1); } catch (IllegalAccessException e) { throw new ObjectComparatorException(e); } catch (IllegalArgumentException e) { throw e; } catch (InvocationTargetException e) { throw new ObjectComparatorException(e); } try { v2 = m2.invoke(v2); } catch (IllegalAccessException e) { throw new ObjectComparatorException(e); } catch (IllegalArgumentException e) { throw e; } catch (InvocationTargetException e) { throw new ObjectComparatorException(e); } } } } int result = new ObjectComparatorImpl(new ComparatorItem(null, asc, ignoreCase, nullIsFirst)).compare(v1, v2); if (result != 0) { return result; } return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(o1, o2); }
From source file:org.eclipse.equinox.servletbridge.FrameworkLauncher.java
private void registerRestartHandler(Class starterClazz) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InvocationTargetException { Method registerFrameworkShutdownHandler = null; try {/*from w ww. j a v a2 s . c om*/ registerFrameworkShutdownHandler = starterClazz.getDeclaredMethod("internalAddFrameworkShutdownHandler", //$NON-NLS-1$ new Class[] { Runnable.class }); } catch (NoSuchMethodException e) { // Ok. However we will not support restart events. Log this as info context.log(starterClazz.getName() + " does not support setting a shutdown handler. Restart handling is disabled."); //$NON-NLS-1$ return; } if (!registerFrameworkShutdownHandler.isAccessible()) registerFrameworkShutdownHandler.setAccessible(true); Runnable restartHandler = createRestartHandler(); registerFrameworkShutdownHandler.invoke(null, new Object[] { restartHandler }); }
From source file:com.p5solutions.core.utils.ReflectionUtility.java
/** * Invoke./*from ww w . j a v a 2s . c om*/ * * @param <O> * the generic type * @param <I> * the generic type * @param object * the object * @param method * the method * @param ignoreAccess * the ignore access * @param args * the args * @return the object */ @SuppressWarnings("unchecked") public static <O, I> O invokeWithAccessWithArguments(I object, Method method, boolean ignoreAccess, Object... args) { if (object == null) { throw new RuntimeException("Object cannot be null when invoking its methods"); } Object returnObject = null; Class<?> clazz = object.getClass(); try { /* call the method */ if (method != null) { if (AopUtils.isAopProxy(object)) { InvocationHandler handler = Proxy.getInvocationHandler(object); returnObject = handler.invoke(object, method, args); } else { boolean isAccessible = method.isAccessible(); try { if (!isAccessible && ignoreAccess) { method.setAccessible(true); } returnObject = method.invoke(object, args); } finally { if (ignoreAccess) { method.setAccessible(isAccessible); } } } } else { throw new RuntimeException("Method cannot be null"); } } catch (Throwable e) { // get the target class if its a proxy clazz = AopUtils.getTargetClass(object); /* Logger that is available to subclasses */ Log logger = LogFactory.getLog(clazz); // logger.error("Unable to invoke method " + method.getName() + " within " // + clazz.getCanonicalName() + "\n" // + getStackTrace(e)); throw new RuntimeException(e); } return (O) returnObject; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }// ww w . jav a2 s .c o m final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }