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

The following examples show how to use java.lang.reflect.Method#getDeclaringClass() . These examples are extracted from open source projects. 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
/**
    * Create a new instance
    * @param marshal Method to be used
    */
public ReflectionMethodImplementor(Method marshal) {

	if (marshal.getParameterTypes().length == 0 && Modifier.isStatic(marshal.getModifiers())) {
		throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
	} else if (marshal.getParameterTypes().length == 1 && (!Modifier.isStatic(marshal.getModifiers()))) {
		throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
	} else if (marshal.getParameterTypes().length >= 2) {
		throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
	}

	if (!marshal.getDeclaringClass().equals(marshal.getReturnType())) {
		throw new IllegalStateException("marshal method must return an instance of target class");
	}

	this.boundClass = marshal.getDeclaringClass();

	try {
		marshal.setAccessible(true);
		this.marshalHandle = LOOKUP.unreflect(marshal);
	} catch (IllegalAccessException e) {
		throw new IllegalStateException("Method is not accessible" + marshal);
	}
}
 
Example 2
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(invoker, args);
    }
    if ("toString".equals(methodName) && parameterTypes.length == 0) {
        return invoker.toString();
    }
    if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
        return invoker.hashCode();
    }
    if ("equals".equals(methodName) && parameterTypes.length == 1) {
        return invoker.equals(args[0]);
    }
    return invoker.invoke(new RpcInvocation(method, args)).recreate();
}
 
Example 3
/**
 * Finds method that is accessible from public class or interface through class hierarchy.
 *
 * @param method  object that represents found method
 * @return object that represents accessible method
 * @throws NoSuchMethodException if method is not accessible or is not found
 *                               in specified superclass or interface
 */
public static Method findAccessibleMethod(Method method) throws NoSuchMethodException {
    Class<?> type = method.getDeclaringClass();
    if (Modifier.isPublic(type.getModifiers()) && isPackageAccessible(type)) {
        return method;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        throw new NoSuchMethodException("Method '" + method.getName() + "' is not accessible");
    }
    for (Type generic : type.getGenericInterfaces()) {
        try {
            return findAccessibleMethod(method, generic);
        }
        catch (NoSuchMethodException exception) {
            // try to find in superclass or another interface
        }
    }
    return findAccessibleMethod(method, type.getGenericSuperclass());
}
 
Example 4
public Object invoke( Object proxy, Method method, Object[] args )
    throws Throwable
{
    // Note that the declaring class in method is the interface
    // in which the method was defined, not the proxy class.
    Class cls = method.getDeclaringClass() ;
    InvocationHandler handler =
        (InvocationHandler)classToInvocationHandler.get( cls ) ;

    if (handler == null) {
        if (defaultHandler != null)
            handler = defaultHandler ;
        else {
            ORBUtilSystemException wrapper = ORBUtilSystemException.get(
                CORBALogDomains.UTIL ) ;
            throw wrapper.noInvocationHandler( "\"" + method.toString() +
                "\"" ) ;
        }
    }

    // handler should never be null here.

    return handler.invoke( proxy, method, args ) ;
}
 
Example 5
@Override
public boolean permitsStaticMethod(@Nonnull Method method, @Nonnull Object[] args) {
    final Class<?> aClass = method.getDeclaringClass();
    final Package aPackage = aClass.getPackage();

    if (aPackage == null) {
        return false;
    }

    if (!aPackage.getName().equals(ORG_APACHE_COMMONS_CSV)) {
        return false;
    }

    if (aClass == CSVFormat.class) {
        return (method.getName().equals("newFormat") || method.getName().equals("valueOf"));
    }

    return false;
}
 
Example 6
private MethodPosition getIndexOfMethodPosition(final Method method)
{
    if (method.getAnnotation(Ignore.class) == null)
    {
        final Class<?> aClass = method.getDeclaringClass();
        return getIndexOfMethodPosition(aClass, method.getName());
    }
    else
    {
        return new NullMethodPosition();
    }
}
 
Example 7
Source Project: tomee   File: EJBRequest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void setMethodInstance(final Method methodInstance) {
    if (methodInstance == null) {
        throw new NullPointerException("methodInstance input parameter is null");
    }
    this.methodInstance = methodInstance;
    this.methodName = methodInstance.getName();
    this.methodParamTypes = methodInstance.getParameterTypes();
    final Class methodClass = methodInstance.getDeclaringClass();

    if (ejb.homeClass != null) {
        if (methodClass.isAssignableFrom(ejb.homeClass)) {
            this.interfaceClass = ejb.homeClass;
            return;
        }
    }

    if (ejb.remoteClass != null) {
        if (methodClass.isAssignableFrom(ejb.remoteClass)) {
            this.interfaceClass = ejb.remoteClass;
            return;
        }
    }

    for (final Class businessClass : ejb.businessClasses) {
        if (methodClass.isAssignableFrom(businessClass)) {
            this.interfaceClass = businessClass;
            return;
        }
    }
}
 
Example 8
Source Project: dubbox   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isBeanPropertyWriteMethod(Method method) {
    return method != null
        && Modifier.isPublic(method.getModifiers())
        && ! Modifier.isStatic(method.getModifiers())
        && method.getDeclaringClass() != Object.class
        && method.getParameterTypes().length == 1
        && method.getName().startsWith("set")
        && method.getName().length() > 3;
}
 
Example 9
private Class checkAndGetEventParamType(Method method){
    Class<?>[] exeParams = method.getParameterTypes();
    if (exeParams.length == 0){
        throw new ColaException("Execute method in "+method.getDeclaringClass()+" should at least have one parameter");
    }
    if(!EventI.class.isAssignableFrom(exeParams[0]) ){
        throw new ColaException("Execute method in "+method.getDeclaringClass()+" should be the subClass of Event");
    }
    return exeParams[0];
}
 
Example 10
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 11
Source Project: azeroth   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isBeanPropertyReadMethod(Method method) {
    return method != null
            && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers())
            && method.getReturnType() != void.class
            && method.getDeclaringClass() != Object.class
            && method.getParameterTypes().length == 0
            && ((method.getName().startsWith("get") && method.getName()
            .length() > 3) || (method.getName().startsWith("is") && method
            .getName().length() > 2));
}
 
Example 12
Source Project: java-technology-stack   File: AutowireUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return whether the setter method of the given bean property is defined
 * in any of the given interfaces.
 * @param pd the PropertyDescriptor of the bean property
 * @param interfaces the Set of interfaces (Class objects)
 * @return whether the setter method is defined by an interface
 */
public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set<Class<?>> interfaces) {
	Method setter = pd.getWriteMethod();
	if (setter != null) {
		Class<?> targetClass = setter.getDeclaringClass();
		for (Class<?> ifc : interfaces) {
			if (ifc.isAssignableFrom(targetClass) &&
					ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) {
				return true;
			}
		}
	}
	return false;
}
 
Example 13
Source Project: JDKSourceCode1.8   File: Introspector.java    License: MIT License 5 votes vote down vote up
private static Method[] getPublicDeclaredMethods(Class<?> clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    if (!ReflectUtil.isPackageAccessible(clz)) {
        return new Method[0];
    }
    synchronized (declaredMethodCache) {
        Method[] result = declaredMethodCache.get(clz);
        if (result == null) {
            result = clz.getMethods();
            for (int i = 0; i < result.length; i++) {
                Method method = result[i];
                if (!method.getDeclaringClass().equals(clz)) {
                    result[i] = null; // ignore methods declared elsewhere
                }
                else {
                    try {
                        method = MethodFinder.findAccessibleMethod(method);
                        Class<?> type = method.getDeclaringClass();
                        result[i] = type.equals(clz) || type.isInterface()
                                ? method
                                : null; // ignore methods from superclasses
                    }
                    catch (NoSuchMethodException exception) {
                        // commented out because of 6976577
                        // result[i] = null; // ignore inaccessible methods
                    }
                }
            }
            declaredMethodCache.put(clz, result);
        }
        return result;
    }
}
 
Example 14
/**
 * @param binary Ignite binary.
 * @param method Method.
 */
private static MethodDescriptor forMethod(IgniteBinary binary, Method method) {
    Class<?>[] paramTypes = method.getParameterTypes();

    int[] paramTypeIds = new int[paramTypes.length];

    for (int i = 0; i < paramTypes.length; i++)
        paramTypeIds[i] = binary.typeId(paramTypes[i].getName());

    return new MethodDescriptor(method.getDeclaringClass(), method.getName(), paramTypeIds);
}
 
Example 15
/**
   * Inherited method from Invocation handler All object state requests are
   * delegated to the federated component.
   *
   * All setters and operations() are delegated to the function service.
   *
   * Notification emmitter methods are also delegated to the function service
   */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {

    if (logger.finerEnabled()) {
      logger.finer(THIS_COMPONENT + ": Invoking Method " + method.getName());
    }
    final Class methodClass = method.getDeclaringClass();



    if (methodClass.equals(NotificationBroadcaster.class)
        || methodClass.equals(NotificationEmitter.class))
      return invokeBroadcasterMethod(proxy, method, args);

    final String methodName = method.getName();
    final Class[] paramTypes = method.getParameterTypes();
    final Class returnType = method.getReturnType();



    final int nargs = (args == null) ? 0 : args.length;

    if (methodName.equals("setLastRefreshedTime")) {
      proxyImpl.setLastRefreshedTime((Long) args[0]);
      return null;
    }
    if (methodName.equals("getLastRefreshedTime")) {
      return proxyImpl.getLastRefreshedTime();
    }

    if (methodName.equals("sendNotification")) {
      sendNotification(args[0]);
      return null;
    }

    // local or not: equals, toString, hashCode
    if (shouldDoLocally(proxy, method)){
      return doLocally(proxy, method, args);
    }

    // Support For MXBean open types
    if (isMXBean) {
      MXBeanProxyInvocationHandler p = findMXBeanProxy(objectName, methodClass, this);
      return p.invoke( proxy, method, args);
    }

    if (methodName.startsWith("get") && methodName.length() > 3 && nargs == 0
        && !returnType.equals(Void.TYPE)) {
      return delegateToObjectState(methodName.substring(3));
    }

    if (methodName.startsWith("is")
        && methodName.length() > 2
        && nargs == 0
        && (returnType.equals(Boolean.TYPE) || returnType.equals(Boolean.class))) {
      return delegateToObjectState(methodName.substring(2));
    }

    final String[] signature = new String[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++)
      signature[i] = paramTypes[i].getName();

//    if (methodName.startsWith("set") && methodName.length() > 3 && nargs == 1
//        && returnType.equals(Void.TYPE)) {
//      return delegateToFunctionService(objectName, methodName, args, signature); // TODO: Abhishek what's the diff between this & delegation below
//
//    }

    return delegateToFunctionService(objectName, methodName, args, signature);

  }
 
Example 16
Source Project: gridgo   File: MethodAccessors.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T buildStaticMethodAccessor(Method method, Class<T> theInterface, String interfaceFunctionName,
        String interfaceReturnTypeName) {
    try {
        Class<?> target = method.getDeclaringClass();
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(target));

        String className = target.getName().replaceAll("\\.", "_") + "_" + method.getName() + "_"
                + System.nanoTime();
        CtClass cc = pool.makeClass(className);

        cc.defrost();
        cc.addInterface(pool.get(theInterface.getName()));

        var paramCount = 0;
        var paramKeys = new StringBuilder();
        var paramValues = new StringBuilder();
        for (var paramType : method.getParameterTypes()) {
            if (paramCount > 0) {
                paramValues.append(", ");
                paramKeys.append(", ");
            }
            var paramName = "param" + paramCount++;
            paramKeys.append("Object " + paramName);
            paramValues.append("(" + paramType.getName() + ") " + paramName);
        }

        var returnValue = target.getName() + "." + method.getName() + "(" + paramValues.toString() + ")";
        var returnType = method.getReturnType();
        if (returnType.isPrimitive() && !returnType.isArray()) {
            var wrappedForReturnType = PrimitiveUtils.getWrapperType(returnType);
            returnValue = wrappedForReturnType.getName() + ".valueOf(" + returnValue + ")";
        }
        var methodCall = ("void".equals(interfaceReturnTypeName) ? "" : "return ") + returnValue;

        String body = "public " + interfaceReturnTypeName + " " + interfaceFunctionName //
                + "(" + paramKeys.toString() + ") { " + methodCall + ";}"; // end of method

        cc.addMethod(CtMethod.make(body, cc));
        return (T) cc.toClass().getConstructor().newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    final Class<?> methodClass = method.getDeclaringClass();

    if (methodClass.equals(NotificationBroadcaster.class)
        || methodClass.equals(NotificationEmitter.class))
        return invokeBroadcasterMethod(proxy, method, args);

    // local or not: equals, toString, hashCode
    if (shouldDoLocally(proxy, method))
        return doLocally(proxy, method, args);

    try {
        if (isMXBean()) {
            MXBeanProxy p = findMXBeanProxy(methodClass);
            return p.invoke(connection, objectName, method, args);
        } else {
            final String methodName = method.getName();
            final Class<?>[] paramTypes = method.getParameterTypes();
            final Class<?> returnType = method.getReturnType();

            /* Inexplicably, InvocationHandler specifies that args is null
               when the method takes no arguments rather than a
               zero-length array.  */
            final int nargs = (args == null) ? 0 : args.length;

            if (methodName.startsWith("get")
                && methodName.length() > 3
                && nargs == 0
                && !returnType.equals(Void.TYPE)) {
                return connection.getAttribute(objectName,
                    methodName.substring(3));
            }

            if (methodName.startsWith("is")
                && methodName.length() > 2
                && nargs == 0
                && (returnType.equals(Boolean.TYPE)
                || returnType.equals(Boolean.class))) {
                return connection.getAttribute(objectName,
                    methodName.substring(2));
            }

            if (methodName.startsWith("set")
                && methodName.length() > 3
                && nargs == 1
                && returnType.equals(Void.TYPE)) {
                Attribute attr = new Attribute(methodName.substring(3), args[0]);
                connection.setAttribute(objectName, attr);
                return null;
            }

            final String[] signature = new String[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++)
                signature[i] = paramTypes[i].getName();
            return connection.invoke(objectName, methodName,
                                     args, signature);
        }
    } catch (MBeanException e) {
        throw e.getTargetException();
    } catch (RuntimeMBeanException re) {
        throw re.getTargetException();
    } catch (RuntimeErrorException rre) {
        throw rre.getTargetError();
    }
    /* The invoke may fail because it can't get to the MBean, with
       one of the these exceptions declared by
       MBeanServerConnection.invoke:
       - RemoteException: can't talk to MBeanServer;
       - InstanceNotFoundException: objectName is not registered;
       - ReflectionException: objectName is registered but does not
         have the method being invoked.
       In all of these cases, the exception will be wrapped by the
       proxy mechanism in an UndeclaredThrowableException unless
       it happens to be declared in the "throws" clause of the
       method being invoked on the proxy.
     */
}
 
Example 18
static boolean hasMoreSpecificClass(Method m1, Method m2) {
    Class<?> m1Class = m1.getDeclaringClass();
    Class<?> m2Class = m2.getDeclaringClass();
    return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
}
 
Example 19
Source Project: orcas   File: GenericTransformer.java    License: Apache License 2.0 4 votes vote down vote up
WritablePropertyImpl( Method pSetter )
{
  super( getPropertyNameForSetter( pSetter ), pSetter.getParameters()[0].getParameterizedType(), pSetter.getDeclaringClass() );
  setter = pSetter;
}
 
Example 20
Source Project: Bytecoder   File: FeatureDescriptor.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Resolves the parameter types of the method.
 *
 * @param base    the class that contains the method in the hierarchy
 * @param method  the object that represents the method
 * @return an array of classes identifying the parameter types of the method
 *
 * @see Method#getGenericParameterTypes
 * @see Method#getParameterTypes
 */
static Class<?>[] getParameterTypes(Class<?> base, Method method) {
    if (base == null) {
        base = method.getDeclaringClass();
    }
    return TypeResolver.erase(TypeResolver.resolveInClass(base, method.getGenericParameterTypes()));
}