Java Code Examples for java.lang.reflect.Method#isAccessible()

The following examples show how to use java.lang.reflect.Method#isAccessible() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractConciergeTestCase.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Call an instance method for given object. The method will be detected
 * based on types of arguments.
 */
public Object callMethod(final Object obj, final String methodName,
		final Object[] args) throws Exception {
	final Class<?> clazz = obj.getClass();
	final Class<?>[] parameterTypes = new Class[args.length];
	for (int i = 0; i < args.length; i++) {
		if (args[i] == null) {
			parameterTypes[i] = Object.class;
		} else {
			parameterTypes[i] = args[i].getClass();
		}
	}
	dumpMethods(clazz);
	dumpDeclaredMethods(clazz);
	final Method method = clazz.getMethod(methodName, parameterTypes);
	if (Modifier.isStatic(method.getModifiers())) {
		throw new RuntimeException(
				"Oops, method " + method.toString() + " is static");
	}
	if (!method.isAccessible()) {
		method.setAccessible(true);
	}
	final Object result = method.invoke(obj, args);
	return result;
}
 
Example 2
Source File: AndroidHack.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static Method findMethod(Object instance, String name,Class<?>... args) throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Method method = clazz.getDeclaredMethod(name,args);

            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return method;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }
    throw new NoSuchMethodException("Method " + name + " not found in " + instance.getClass());
}
 
Example 3
Source File: ReflectUtils.java    From juice with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Returns an accessible method (that is, one that can be invoked via
 * reflection) with given name and parameters. If no such method
 * can be found, return {@code null}.
 *
 * @param clazz get method from this class
 * @param methodName get method with this name
 * @param parameterTypes with these parameters types
 * @return The accessible method
 */
public static Method getAccessibleMethod(final Class<?> clazz, final String methodName,
                                         Class<?>... parameterTypes) {

    // 处理原子类型与对象类型的兼容
    ClassUtils.wrapClasses(parameterTypes);

    for (Class<?> searchType = clazz; searchType != Object.class; searchType = searchType.getSuperclass()) {
        try {
            Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
            if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
                    && !method.isAccessible()) {
                method.setAccessible(true);
            }
            return method;
        } catch (NoSuchMethodException e) {
            // Method不在当前类定义,继续向上转型
        }
    }
    return null;
}
 
Example 4
Source File: ReflectionUtils.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Call a method with its name regardless of accessibility.
 *
 * @param object target object to whom a method is to be invoked
 * @param methodName name of the method
 * @param args arguments for the method
 * @param <T> return type
 * @return return value of the method, null for void methods
 */
@SuppressWarnings("unchecked")
public static <T> T callMethod(Object object, String methodName, Object... args) throws Exception {
  Validate.notNull(object, "null class name");
  Method method = null;
  boolean isAccessible = true;
  try {
    Class<?>[] argTypes = new Class<?>[args.length];
    IntStream.range(0, args.length).forEach(i -> argTypes[i] = args[i].getClass());
    method = findMatchingMethod(object.getClass(), methodName, argTypes);
    if (method == null) {
      throw new NoSuchMethodException(methodName);
    }
    isAccessible = method.isAccessible();
    method.setAccessible(true);
    return (T) method.invoke(object, args);
  } catch (Exception e) {
    LOG.warn("Failed to invoke method: " + methodName, e);
    throw e;
  } finally {
    if (method != null) {
      method.setAccessible(isAccessible);
    }
  }
}
 
Example 5
Source File: BDDFactory.java    From symbolicautomata with Apache License 2.0 6 votes vote down vote up
protected void registerCallback(List callbacks, Object o, Method m) {
    if (!Modifier.isPublic(m.getModifiers()) && !m.isAccessible()) {
        throw new BDDException("Callback method not accessible");
    }
    if (!Modifier.isStatic(m.getModifiers())) {
        if (o == null) {
            throw new BDDException("Base object for callback method is null");
        }
        if (!m.getDeclaringClass().isAssignableFrom(o.getClass())) {
            throw new BDDException("Base object for callback method is the wrong type");
        }
    }
    if (false) {
        Class[] params = m.getParameterTypes();
        if (params.length != 1 || params[0] != int.class) {
            throw new BDDException("Wrong signature for callback");
        }
    }
    callbacks.add(new Object[] { o, m });
}
 
Example 6
Source File: Reflections.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}
 
Example 7
Source File: JavaMethod.java    From luaj with MIT License 5 votes vote down vote up
private JavaMethod(Method m) {
	super( m.getParameterTypes(), m.getModifiers() );
	this.method = m;
	try {
		if (!m.isAccessible())
			m.setAccessible(true);
	} catch (SecurityException s) {
	}
}
 
Example 8
Source File: LoginIdentityProviderFactoryBean.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void performMethodInjection(final LoginIdentityProvider instance, final Class loginIdentityProviderClass)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    for (final Method method : loginIdentityProviderClass.getMethods()) {
        if (method.isAnnotationPresent(LoginIdentityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);

            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 (NiFiProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = loginIdentityProviderClass.getSuperclass();
    if (parentClass != null && LoginIdentityProvider.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}
 
Example 9
Source File: SafeMethod.java    From EchoPet with GNU General Public License v3.0 5 votes vote down vote up
protected void setMethod(Method method) {
    if (method == null) {
        EchoPet.LOG.warning("Cannot create a SafeMethod with a null method!");
    }
    if (!method.isAccessible()) {
        method.setAccessible(true);
    }
    this.method = method;
    this.params = method.getParameterTypes();
    this.isStatic = Modifier.isStatic(method.getModifiers());
}
 
Example 10
Source File: ReflectionUtil.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
public static void makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers()) || !Modifier
            .isPublic(method.getDeclaringClass().getModifiers()))
            && !method.isAccessible()) {
        method.setAccessible(true);
    }
}
 
Example 11
Source File: ReflectUtils.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
public static void makeAccessible(Method method)
{
    if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
            && !method.isAccessible())
    {
        method.setAccessible(true);
    }
}
 
Example 12
Source File: ReflectUtils.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
public static void makeAccessible(Method method)
{
    if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
            && !method.isAccessible())
    {
        method.setAccessible(true);
    }
}
 
Example 13
Source File: RetryInvocationHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
protected Object invokeMethod(Method method, Object[] args) throws Throwable {
  try {
    if (!method.isAccessible()) {
      method.setAccessible(true);
    }
    return method.invoke(currentProxy.proxy, args);
  } catch (InvocationTargetException e) {
    throw e.getCause();
  }
}
 
Example 14
Source File: PublicationManagerImpl.java    From joynr with Apache License 2.0 4 votes vote down vote up
private boolean processFilterChain(PublicationInformation publicationInformation,
                                   List<BroadcastFilter> filters,
                                   Object[] values) {

    if (filters != null && filters.size() > 0) {
        BroadcastSubscriptionRequest subscriptionRequest = (BroadcastSubscriptionRequest) publicationInformation.subscriptionRequest;
        BroadcastFilterParameters filterParameters = subscriptionRequest.getFilterParameters();

        for (BroadcastFilter filter : filters) {
            Method filterMethod = null;
            try {
                Method[] methodsOfFilterClass = filter.getClass().getMethods();
                for (Method method : methodsOfFilterClass) {
                    if (method.getName().equals("filter")) {
                        filterMethod = method;
                        break;
                    }
                }
                if (filterMethod == null) {
                    // no filtering
                    return true;
                }

                if (!filterMethod.isAccessible()) {
                    filterMethod.setAccessible(true);
                }

                Class<?> filterParametersType = filterMethod.getParameterTypes()[values.length];
                BroadcastFilterParameters filterParametersDerived = (BroadcastFilterParameters) filterParametersType.newInstance();
                filterParametersDerived.setFilterParameters(filterParameters.getFilterParameters());
                Object[] args = Arrays.copyOf(values, values.length + 1);
                args[args.length - 1] = filterParametersDerived;

                if ((Boolean) filterMethod.invoke(filter, args) == false) {
                    return false;
                }
            } catch (Exception e) {
                logger.error("ProcessFilterChain error:", e);
                throw new IllegalStateException("processFilterChain: Error in reflection calling filters.", e);
            }
        }
    }
    return true;
}
 
Example 15
Source File: Stringizers.java    From Zebra with Apache License 2.0 4 votes vote down vote up
private void fromPojo(Set<Object> done, LengthLimiter sb, Object obj) {
	Class<? extends Object> type = obj.getClass();

	if (hasToString(type)) {
		fromObject(done, sb, obj.toString());
		return;
	}

	List<Method> getters = Reflects.forMethod().getMethods(type, new Reflects.IMemberFilter<Method>() {
		@Override
		public boolean filter(Method method) {
			return Reflects.forMethod().isGetter(method);
		}
	});

	Collections.sort(getters, new Comparator<Method>() {
		@Override
		public int compare(Method m1, Method m2) {
			return m1.getName().compareTo(m2.getName());
		}
	});

	if (getters.isEmpty()) {
		// use java toString() since we can't handle it
		sb.append(obj.toString());
	} else {
		boolean first = true;

		sb.append('{');

		for (Method getter : getters) {
			String key = Reflects.forMethod().getGetterName(getter);
			Object value;

			try {
				if (!getter.isAccessible()) {
					getter.setAccessible(true);
				}

				value = getter.invoke(obj);
			} catch (Exception e) {
				// ignore it
				value = null;
			}

			if (value == null) {
				continue;
			}

			if (first) {
				first = false;
			} else {
				sb.append(',');

				if (!m_compact) {
					sb.append(' ');
				}
			}

			sb.append('"').append(key).append("\":");

			if (!m_compact) {
				sb.append(' ');
			}

			fromObject(done, sb, value);
		}

		sb.append('}');
	}
}
 
Example 16
Source File: BeanUtils.java    From lemon with Apache License 2.0 4 votes vote down vote up
public static Object invokeMethod(Object object, String methodName,
        boolean targetAccessible, Object... params)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    Assert.notNull(object);
    Assert.hasText(methodName);

    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 {
            method = superClass.getDeclaredMethod(methodName, types);

            break;
        } catch (NoSuchMethodException ex) {
            // 方法不在当前类定义,继续向上转型
            logger.debug(ex.getMessage(), ex);
        }
    }

    if (method == null) {
        throw new NoSuchMethodException("No Such Method : "
                + clazz.getSimpleName() + "." + methodName
                + Arrays.asList(types));
    }

    boolean accessible = method.isAccessible();
    method.setAccessible(targetAccessible);

    Object result = method.invoke(object, params);

    method.setAccessible(accessible);

    return result;
}
 
Example 17
Source File: ServcesManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void handleCreateServiceOne(Context hostContext, Intent stubIntent, ServiceInfo info) throws Exception {
    //            CreateServiceData data = new CreateServiceData();
    //            data.token = fakeToken;// IBinder
    //            data.info =; //ServiceInfo
    //            data.compatInfo =; //CompatibilityInfo
    //            data.intent =; //Intent
    //            activityThread.handleCreateServiceOne(data);
    //            service = activityThread.mTokenServices.get(fakeToken);
    //            activityThread.mTokenServices.remove(fakeToken);
    ResolveInfo resolveInfo = hostContext.getPackageManager().resolveService(stubIntent, 0);
    ServiceInfo stubInfo = resolveInfo != null ? resolveInfo.serviceInfo : null;
    PluginManager.getInstance().reportMyProcessName(stubInfo.processName, info.processName, info.packageName);
    PluginProcessManager.preLoadApk(hostContext, info);
    Object activityThread = ActivityThreadCompat.currentActivityThread();
    IBinder fakeToken = new MyFakeIBinder();
    Class CreateServiceData = Class.forName(ActivityThreadCompat.activityThreadClass().getName() + "$CreateServiceData");
    Constructor init = CreateServiceData.getDeclaredConstructor();
    if (!init.isAccessible()) {
        init.setAccessible(true);
    }
    Object data = init.newInstance();

    FieldUtils.writeField(data, "token", fakeToken);
    FieldUtils.writeField(data, "info", info);
    if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
        FieldUtils.writeField(data, "compatInfo", CompatibilityInfoCompat.DEFAULT_COMPATIBILITY_INFO());
    }

    Method method = activityThread.getClass().getDeclaredMethod("handleCreateService", CreateServiceData);
    if (!method.isAccessible()) {
        method.setAccessible(true);
    }
    method.invoke(activityThread, data);
    Object mService = FieldUtils.readField(activityThread, "mServices");
    Service service = (Service) MethodUtils.invokeMethod(mService, "get", fakeToken);
    MethodUtils.invokeMethod(mService, "remove", fakeToken);
    mTokenServices.put(fakeToken, service);
    mNameService.put(info.name, service);


    if (stubInfo != null) {
        PluginManager.getInstance().onServiceCreated(stubInfo, info);
    }
}
 
Example 18
Source File: JavassistLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Object invoke(
		final Object proxy,
		final Method thisMethod,
		final Method proceed,
		final Object[] args) throws Throwable {
	if ( this.constructed ) {
		Object result;
		try {
			result = this.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();
               }
		}
		else {
			return result;
		}
	}
	else {
		// while constructor is running
		if ( thisMethod.getName().equals( "getHibernateLazyInitializer" ) ) {
			return this;
		}
		else {
			return proceed.invoke( proxy, args );
		}
	}
}
 
Example 19
Source File: ReflectionUtils.java    From tangyuan2 with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Make the given method accessible, explicitly setting it accessible if necessary. The {@code setAccessible(true)}
 * method is only called when actually necessary, to avoid unnecessary conflicts with a JVM SecurityManager (if
 * active).
 * 
 * @param method
 *        the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}
 
Example 20
Source File: ReflectionUtils.java    From dolphin with Apache License 2.0 3 votes vote down vote up
/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param method the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) ||
			!Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
		method.setAccessible(true);
	}
}