/** 改变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); } }
protected Serializable fieldValue(final Object obj, final AnnotatedElement annotatedElement) { if (annotatedElement instanceof Field) { // a field final Field f = (Field) annotatedElement; if (!f.isAccessible()) { f.setAccessible(true); } try { return (Serializable) f.get(obj); } catch (final IllegalArgumentException e) { logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e); } catch (final IllegalAccessException e) { logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e); } catch (final ClassCastException e) { logger.warn(obj.getClass().getName() + "的id字段" + f.getName() + "不可序列化。", e); } } else { // a method final Method m = (Method) annotatedElement; if (!m.isAccessible()) { m.setAccessible(true); } try { return (Serializable) ReflectionUtils.invokeMethod(m, obj); } catch (final ClassCastException e) { logger.warn(obj.getClass().getName() + "的id字段" + m.getName() + "不可序列化。", e); } } return null; }
public Object doGetValue() { try { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null) { throw new BindingException( propertyDescriptor.getName() + " property does not have a read method."); // $NON-NLS-1$ } if (!readMethod.isAccessible()) { readMethod.setAccessible(true); } return readMethod.invoke(object, null); } catch (InvocationTargetException e) { /* * InvocationTargetException wraps any exception thrown by the * invoked method. */ throw new RuntimeException(e.getCause()); } catch (Exception e) { if (BeansObservables.DEBUG) { Policy.getLog() .log( new Status( IStatus.WARNING, Policy.JFACE_DATABINDING, IStatus.OK, "Could not read value of " + object + "." + propertyDescriptor.getName(), e)); //$NON-NLS-1$ //$NON-NLS-2$ } return null; } }
public void doSetValue(Object value) { updating = true; try { Object oldValue = doGetValue(); Method writeMethod = propertyDescriptor.getWriteMethod(); if (!writeMethod.isAccessible()) { writeMethod.setAccessible(true); } writeMethod.invoke(object, new Object[] {value}); fireValueChange(Diffs.createValueDiff(oldValue, doGetValue())); } catch (InvocationTargetException e) { /* * InvocationTargetException wraps any exception thrown by the * invoked method. */ throw new RuntimeException(e.getCause()); } catch (Exception e) { if (BeansObservables.DEBUG) { Policy.getLog() .log( new Status( IStatus.WARNING, Policy.JFACE_DATABINDING, IStatus.OK, "Could not change value of " + object + "." + propertyDescriptor.getName(), e)); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { updating = false; } }
public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; SpringExtensionFactory.addApplicationContext(applicationContext); if (applicationContext != null) { SPRING_CONTEXT = applicationContext; try { Method method = applicationContext .getClass() .getMethod( "addApplicationListener", new Class<?>[] {ApplicationListener.class}); // 兼容Spring2.0.1 method.invoke(applicationContext, new Object[] {this}); supportedApplicationListener = true; } catch (Throwable t) { if (applicationContext instanceof AbstractApplicationContext) { try { Method method = AbstractApplicationContext.class.getDeclaredMethod( "addListener", new Class<?>[] {ApplicationListener.class}); // 兼容Spring2.0.1 if (!method.isAccessible()) { method.setAccessible(true); } method.invoke(applicationContext, new Object[] {this}); supportedApplicationListener = true; } catch (Throwable t2) { } } } } }
private JarURLConnection openJarURLConnection(final URL url) throws IOException { final URL checkedUrl; if ("zip".equals(url.getProtocol())) { // WebLogic returns URL with "zip" protocol, returning a // weblogic.utils.zip.ZipURLConnection when opened // Easy fix is to convert this URL to jar URL checkedUrl = new URL(url.toExternalForm().replace("zip:/", "jar:file:/")); } else { checkedUrl = url; } URLConnection urlConnection = checkedUrl.openConnection(); // GlassFish 4.1.1 is providing a URLConnection of type: // http://svn.apache.org/viewvc/felix/trunk/framework/src/main/java/org/ // apache/felix/framework/URLHandlersBundleURLConnection.java?view=markup // Which does _not_ extend JarURLConnection. // This bit of reflection allows us to call the getLocalURL method which // actually returns a URL to a jar file. if (checkedUrl.getProtocol().startsWith("bundle")) { try { final Method m = urlConnection.getClass().getDeclaredMethod("getLocalURL"); if (!m.isAccessible()) { m.setAccessible(true); } final URL jarUrl = (URL) m.invoke(urlConnection); urlConnection = jarUrl.openConnection(); } catch (Exception ex) { throw new AssertionError("Couldn't read jar file URL from bundle: " + ex); } } if (urlConnection instanceof JarURLConnection) { return (JarURLConnection) urlConnection; } else { throw new AssertionError("Unknown URLConnection type: " + urlConnection.getClass().getName()); } }
@Override public Object invokeImpl(Object proxy, Method method, Object[] args) throws SentryUserException { Object result = null; try { if (!method.isAccessible()) { method.setAccessible(true); } // The client is initialized in the first call instead of constructor. // This way we can propagate the connection exception to caller cleanly if (client == null) { renewSentryClient(); } result = method.invoke(client, args); } catch (IllegalAccessException e) { throw new SentryUserException(e.getMessage(), e.getCause()); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof SentryUserException) { throw (SentryUserException) e.getTargetException(); } else { LOGGER.warn( THRIFT_EXCEPTION_MESSAGE + ": Error in connect current" + " service, will retry other service.", e); if (client != null) { client.close(); client = null; } } } catch (IOException e1) { throw new SentryUserException("Error connecting to sentry service " + e1.getMessage(), e1); } return result; }
/** * Invoke the method on the instance, with any arguments specified, casting the result of invoking * the method to the expected return type. * * <p> * * <p>This method wraps {@link Method#invoke(Object, Object...)}, converting the checked * exceptions that {@link Method#invoke(Object, Object...)} specifies to runtime exceptions. * * <p> * * <p>If instructed, this method attempts to set the accessible flag of the method in a {@link * PrivilegedAction} before invoking the method. * * @param setAccessible flag indicating whether method should first be set as accessible * @param method the method to invoke * @param instance the instance to invoke the method * @param args the arguments to the method * @return the result of invoking the method, or null if the method's return type is void * @throws RuntimeException if this <code>Method</code> object enforces Java language access * control and the underlying method is inaccessible or if the underlying method throws an * exception or if the initialization provoked by this method fails. * @throws IllegalArgumentException if the method is an instance method and the specified <code> * instance</code> argument is not an instance of the class or interface declaring the * underlying method (or of a subclass or implementor thereof); if the number of actual and * formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, * after possible unwrapping, a parameter value cannot be converted to the corresponding * formal parameter type by a method invocation conversion. * @throws NullPointerException if the specified <code>instance</code> is null and the method is * an instance method. * @throws ClassCastException if the result of invoking the method cannot be cast to the * expectedReturnType * @throws ExceptionInInitializerError if the initialization provoked by this method fails. * @see Method#invoke(Object, Object...) */ public static <T> T invokeMethod( boolean setAccessible, Method method, Class<T> expectedReturnType, Object instance, Object... args) { if (setAccessible && !method.isAccessible()) { setAccessible(method); } try { return expectedReturnType.cast(method.invoke(instance, args)); } catch (IllegalAccessException ex) { throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(buildInvokeMethodErrorMessage(method, instance, args), ex); } catch (InvocationTargetException ex) { throw new RuntimeException( buildInvokeMethodErrorMessage(method, instance, args), ex.getCause()); } catch (NullPointerException ex) { NullPointerException ex2 = new NullPointerException(buildInvokeMethodErrorMessage(method, instance, args)); ex2.initCause(ex.getCause()); throw ex2; } catch (ExceptionInInitializerError e) { ExceptionInInitializerError e2 = new ExceptionInInitializerError(buildInvokeMethodErrorMessage(method, instance, args)); e2.initCause(e.getCause()); throw e2; } }
/** * Call preDestroy method on the specified instance recursively from deepest superclass to actual * class. * * @param instance object to call preDestroy methods on * @param clazz (super) class to examine for preDestroy annotation. * @throws IllegalAccessException if preDestroy method is inaccessible. * @throws java.lang.reflect.InvocationTargetException if call fails */ protected void preDestroy(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { preDestroy(instance, superClass); } // At the end the postconstruct annotated // method is invoked List<AnnotationCacheEntry> annotations = null; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } if (annotations == null) { // instance not created through the instance manager return; } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.PRE_DESTROY) { Method preDestroy = getMethod(clazz, entry); synchronized (preDestroy) { boolean accessibility = preDestroy.isAccessible(); preDestroy.setAccessible(true); preDestroy.invoke(instance); preDestroy.setAccessible(accessibility); } } } }
@Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { if (this.member instanceof Method) { Method method = (Method) this.member; try { if (this.needsToBeMadeAccessible && !method.isAccessible()) { method.setAccessible(true); } Object value = method.invoke(target); return new TypedValue(value, this.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException( "Unable to access property '" + name + "' through getter method", ex); } } else { Field field = (Field) this.member; try { if (this.needsToBeMadeAccessible && !field.isAccessible()) { field.setAccessible(true); } Object value = field.get(target); return new TypedValue(value, this.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } }
/** * Constructs a new RegisteredEventListener surrounding the given {@code listenerMethod} of the * provided {@code listener} object. * * @param listenerMethod The event handler method to be wrapped by this RegisteredEventListener. * @param listener The object on which {@code method} is to be called. * @throws IllegalArgumentException If {@code listenerMethod} does not have an EventListener * annotation or if {@code listenerMthod} does not accept a single {@link Event} subclass * object as a parameter. */ public RegisteredEventListener(Method listenerMethod, Listener listener) { // Attempt to get the EventListener annotation on this method EventListener listenerAnnotation = listenerMethod.getAnnotation(EventListener.class); if (listenerAnnotation == null) { // No annotation, throw exception throw new IllegalArgumentException( "Listener method does not have an EventListener annotation."); } // Get priority and ignoreCancelled values from the annotation priority = listenerAnnotation.priority(); ignoresCancelled = listenerAnnotation.ignoreCancelled(); // Get the parameter types of the method Class<?>[] listenerMethodParameters = listenerMethod.getParameterTypes(); // Verify that the parameters of the method are valid for an event-handling method if (listenerMethodParameters.length != 1 || !Event.class.isAssignableFrom(listenerMethodParameters[0])) { // Parameters are invalid, throw exception throw new IllegalArgumentException( "Listener method signature invalid. Does not have a single Event subclass parameter."); } // Store the type of the Event-subclass parameter in eventType eventType = (Class<? extends Event>) listenerMethodParameters[0]; // Store the listener method in listenerMethod this.listenerMethod = listenerMethod; // Make sure that listenerMethod is accessible if (!listenerMethod.isAccessible()) { listenerMethod.setAccessible(true); } // Store the listener object in listener this.listener = listener; }
private Object invokeMethod(Method method, Object[] args) throws Throwable { try { if (!method.isAccessible()) { method.setAccessible(true); } return method.invoke(currentProxy, args); } catch (InvocationTargetException e) { throw e.getCause(); } }
/** * Inject value from jndi into a setter method of an instance * * @param method * @param injectable */ protected void injectMethod(Method method, Object injectable) { try { boolean accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(injectable, new Object[] {lookupInjectedValue()}); method.setAccessible(accessibility); } catch (Exception e) { LOG.warn(e); throw new IllegalStateException("Inject failed for method " + method.getName()); } }
@Test public void test_niet_bestaan_setters() { Method[] lijst = DIV.class.getDeclaredMethods(); boolean probleem = false; for (Method m : lijst) { probleem &= m.isAccessible() && m.getName().startsWith("set"); } if (probleem) { fail("there is a setter method in DIV"); } }
public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception { Method method = clazz.getDeclaredMethod(name, parameterTypes); if (!method.isAccessible()) { method.setAccessible(true); } return method; }
/** * Adds the URL to the system class loader classpath using reflection. HACK: Uses reflection to * modify the class path, and assumes loader is a URLClassLoader. * * @param urls URLs to add to the system class loader classpath. */ private static void addClasspath(List<URL> urls) { Set<URL> existing = JVMUtils.getClasspathURLs(); for (URL url : urls) { if (existing.contains(url)) continue; try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); if (!method.isAccessible()) method.setAccessible(true); method.invoke(ClassLoader.getSystemClassLoader(), url); } catch (Exception e) { throw new ReviewedStingException("Error adding url to the current classloader.", e); } } }
private static final Method getDeclaredMethod( Class<?> owner, String methodName, Class<?>... parameterTypes) throws SecurityException, NoSuchMethodException { Method m = owner.getDeclaredMethod(methodName, parameterTypes); if (!m.isAccessible()) { m.setAccessible(true); } return m; }
public QQNotifyHandlerProxy(Object proxyObject) { this.proxyObject = proxyObject; this.methodMap = new HashMap<QQNotifyEvent.Type, Method>(); for (Method m : proxyObject.getClass().getDeclaredMethods()) { if (m.isAnnotationPresent(QQNotifyHandler.class)) { QQNotifyHandler handler = m.getAnnotation(QQNotifyHandler.class); this.methodMap.put(handler.value(), m); if (!m.isAccessible()) { m.setAccessible(true); } } } }
@Override public Object getValue(Object pojo, Method method, Object[] args) throws Throwable { Method targetMethod = getMethodWithMapping(pojo, method, args); if (targetMethod == null) { throw new RuntimeException("Internal error, isEligible() should be called first!"); } if (!targetMethod.isAccessible()) { targetMethod.setAccessible(true); } return convertedValue(targetMethod.invoke(pojo, args), method.getReturnType()); }
static { if (VERSION.SDK_INT >= 18) { try { sComputeFitSystemWindowsMethod = View.class.getDeclaredMethod( "computeFitSystemWindows", new Class[] {Rect.class, Rect.class}); if (!sComputeFitSystemWindowsMethod.isAccessible()) { sComputeFitSystemWindowsMethod.setAccessible(true); } } catch (NoSuchMethodException e) { Log.d("ViewUtils", "Could not find method computeFitSystemWindows. Oh well."); } } }
@Nullable @SuppressWarnings("unchecked") public static <T> T invoke(@Nullable Object target, @NonNull Method method, Object... args) throws DynamicException { final boolean isAccessible = method.isAccessible(); try { method.setAccessible(true); return (T) method.invoke(target, args); } catch (InvocationTargetException | IllegalAccessException e) { throw new DynamicException(e); } finally { method.setAccessible(isAccessible); } }
private static Callback createBeanCallback(Class<?> callbackClass, String methodName) { Class<?> callbackSuperclass = callbackClass.getSuperclass(); if (callbackSuperclass != null) { Callback callback = createBeanCallback(callbackSuperclass, methodName); if (callback != null) return callback; } for (Method method : callbackClass.getDeclaredMethods()) { if (!method.getName().equals(methodName)) continue; if (method.getParameterTypes().length != 0) continue; if (!method.isAccessible()) method.setAccessible(true); return new BeanCallback(method); } return null; }
/* * (non-Javadoc) * * @see com.absir.aop.AopProxyHandler#invoke(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[], * net.sf.cglib.proxy.MethodProxy) */ @Override public Object invoke(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if (beanObject == null) { return methodProxy.invokeSuper(proxy, args); } else { if (!method.isAccessible()) { method.setAccessible(true); } return method.invoke(beanObject, args); } }
/** * Add a URL to the Minecraft classloader class path * * @param classUrl URL of the resource to add */ private boolean addURLToClassPath(URL classUrl) { try { if (Minecraft.class.getClassLoader() instanceof URLClassLoader && mAddUrl != null && mAddUrl.isAccessible()) { URLClassLoader classLoader = (URLClassLoader) Minecraft.class.getClassLoader(); mAddUrl.invoke(classLoader, classUrl); return true; } } catch (Throwable th) { logger.log(Level.WARNING, "Error adding class path entry", th); } return false; }
Object invokeMethod( XWalkExtensionClient ext, int instanceID, Object obj, String mName, JSONArray args) throws ReflectiveOperationException { if (!hasMethod(mName)) { throw new NoSuchMethodException("No such method:" + mName); } if (!(getMemberInfo(mName).isStatic) && !(myClass.isInstance(obj))) { throw new InvocationTargetException(new Exception("Invalid target to set property:" + mName)); } Method m = (Method) members.get(mName).accesser; if (!m.isAccessible()) { m.setAccessible(true); } Object[] oArgs = getArgsFromJson(ext, instanceID, m, args); return m.invoke(obj, oArgs); }
/** * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String) * <p>This method was added in the Servlet 2.3 API however the OSGi HttpService currently does * not provide support for this method in the HttpContext interface. To support * "getResourcePaths(...) this implementation uses reflection to check for and then call the * associated HttpContext.getResourcePaths(...) method opportunistically. Null is returned if * the method is not present or fails. */ @SuppressWarnings("unchecked") public Set<String> getResourcePaths(String name) { if (name == null || !name.startsWith("/")) // $NON-NLS-1$ return null; try { Method getResourcePathsMethod = httpContext .getClass() .getMethod("getResourcePaths", new Class[] {String.class}); // $NON-NLS-1$ if (!getResourcePathsMethod.isAccessible()) getResourcePathsMethod.setAccessible(true); return (Set<String>) getResourcePathsMethod.invoke(httpContext, new Object[] {name}); } catch (Exception e) { // ignore } return null; }
protected Object callMethod(Object o, Class<?> clazz, String name) { try { Method m = clazz.getDeclaredMethod(name); boolean prev = m.isAccessible(); m.setAccessible(true); try { return m.invoke(o); } finally { m.setAccessible(prev); } } catch (ReflectiveOperationException e) { return e; } catch (SecurityException e) { return e; } }
private static Object invoke(Object o, Method m) throws IllegalAccessException, InvocationTargetException { boolean access = m.isAccessible(); m.setAccessible(true); try { LazyLoadScenario.setShouldLoad(false); return m.invoke(o); } catch (Exception e) { // That's fine return null; } finally { LazyLoadScenario.setShouldLoad(true); m.setAccessible(access); } }
public Object serviceInvokation( String actor, String serviceName, String methodName, Object[] methodParams) throws NotFoundException, ServiceException, IMTPException { AID id = new AID(actor, AID.ISLOCALNAME); AgentImage image = getAgentImage(id); ServiceHelper helper = image.getHelper(serviceName); if (helper == null) { throw new ServiceException("Service " + serviceName + "does not have a Service-helper"); } BECodec codec = getBECodec(serviceName); Object[] decodedParams = codec.decodeParams(methodName, methodParams); try { Method m = null; Method[] mm = helper.getClass().getMethods(); for (int i = 0; i < mm.length; ++i) { if (mm[i].getName().equals(methodName)) { if (isCompatible(mm[i], decodedParams)) { m = mm[i]; break; } } } if (m != null) { if (!m.isAccessible()) { try { m.setAccessible(true); } catch (SecurityException se) { throw new NoSuchMethodException( "Method " + methodName + "() of class " + getClass().getName() + " not accessible."); } } Object result = m.invoke(helper, decodedParams); return codec.encodeResult(methodName, result); } else { throw new ServiceException("No valid " + methodName + " method found in service helper"); } } catch (ServiceException se) { throw se; } catch (Exception e) { e.printStackTrace(); throw new ServiceException("Unexpected error, ", e); } }
public static void makeOptionalFitsSystemWindows(View view) { if (VERSION.SDK_INT >= 16) { try { Method method = view.getClass().getMethod("makeOptionalFitsSystemWindows", new Class[0]); if (!method.isAccessible()) { method.setAccessible(true); } method.invoke(view, new Object[0]); } catch (NoSuchMethodException e) { Log.d("ViewUtils", "Could not find method makeOptionalFitsSystemWindows. Oh well..."); } catch (InvocationTargetException e2) { Log.d("ViewUtils", "Could not invoke makeOptionalFitsSystemWindows", e2); } catch (IllegalAccessException e3) { Log.d("ViewUtils", "Could not invoke makeOptionalFitsSystemWindows", e3); } } }