Java Code Examples for java.lang.reflect.Method.getReturnType()

The following are Jave code examples for showing how to use getReturnType() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Notebook   File: Reflections.java   View Source Code Vote up 7 votes
public Reflections callMethod(String methodName, MethodCallback callback, Object ... params) {
	try {
		Class[] parameterTypes = types(params);
		Method method = getMethod(methodName,parameterTypes);
		method.setAccessible(true);
		if(method.getReturnType() == void.class){
			method.invoke(object, params);
		}else{
			Object returnValue = method.invoke(object, params);
			if(callback != null) callback.done(returnValue);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return this;
}
 
Example 2
Project: goku-jdbc   File: GokuInvocationHandler.java   View Source Code Vote up 7 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        Object ret = method.invoke(orig, args);
        Class<?> returnType = method.getReturnType();
        if (WRAP_TARGET_CLASSES.contains(returnType)) {
            ret = Proxy.newProxyInstance(returnType.getClassLoader(), new Class[]{returnType},
                    new GokuInvocationHandler(ret));
        }
        return ret;
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof SQLException) {
            targetEx = new GokuSQLException((SQLException) targetEx);
        }
        throw targetEx;
    }
}
 
Example 3
Project: GitHub   File: SourceSortOrderIT.java   View Source Code Vote up 6 votes
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void generatedClassesInCorrectPackageForFilesFirstSort() throws ClassNotFoundException, SecurityException,
        NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/sourceSortOrder/", "com.example", config("sourceSortOrder", SourceSortOrder.FILES_FIRST
                    .toString()));

    Class generatedTypeA = resultsClassLoader.loadClass("com.example.A");
    Class generatedTypeZ = resultsClassLoader.loadClass("com.example.Z");

    Method getterTypeA = generatedTypeA.getMethod("getRefToA");
    final Class<?> returnTypeA = getterTypeA.getReturnType();

    Method getterTypeZ = generatedTypeZ.getMethod("getRefToZ");
    final Class<?> returnTypeZ = getterTypeZ.getReturnType();

    assertInPackage("com.example", generatedTypeA);
    assertInPackage("com.example", generatedTypeZ);
    assertInPackage("com.example", returnTypeA);
    assertInPackage("com.example", returnTypeZ);
}
 
Example 4
Project: holon-vaadin   File: ViewNavigationUtils.java   View Source Code Vote up 6 votes
/**
 * Check given method has a valid signature for {@link OnShow} or {@link OnLeave} view method
 * @param viewClass View class
 * @param method Method to check
 * @param message Error message annotation description
 * @throws ViewConfigurationException Method is not valid
 */
private static void checkViewOnShowOrLeaveMethod(Class<?> viewClass, Method method, String message)
		throws ViewConfigurationException {
	if (method.getReturnType() != Void.class && method.getReturnType() != Void.TYPE) {
		throw new ViewConfigurationException("Invalid " + message + " method in view class " + viewClass.getName()
				+ ": method must be a void return method");
	}
	int params = method.getParameterCount();
	if (params > 1) {
		throw new ViewConfigurationException("Invalid " + message + " method in view class " + viewClass.getName()
				+ ": method must have no parameters or only one parameter of type ViewChangeEvent");
	}
	if (params == 1) {
		Parameter param = method.getParameters()[0];
		if (param.isVarArgs() || !(ViewChangeEvent.class.isAssignableFrom(param.getType())
				|| ViewNavigatorChangeEvent.class.isAssignableFrom(param.getType()))) {
			throw new ViewConfigurationException(
					"Invalid " + message + " method in view class " + viewClass.getName()
							+ ": method must have no parameters or only one parameter of type ViewChangeEvent");
		}
	}
}
 
Example 5
Project: bekit   File: FlowParser.java   View Source Code Vote up 6 votes
private static FlowExecutor.TargetMappingExecutor parseTargetMapping(Method method) {
    logger.debug("解析目标对象映射方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验入参
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须只能有一个入参");
    }
    // 校验返回参数
    if (method.getReturnType() != String.class) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "返回参数必须是String类型");
    }

    return new FlowExecutor.TargetMappingExecutor(method, parameterTypes[0]);
}
 
Example 6
Project: OpenJSharp   File: LauncherHelper.java   View Source Code Vote up 6 votes
static void validateMainClass(Class<?> mainClass) {
    Method mainMethod;
    try {
        mainMethod = mainClass.getMethod("main", String[].class);
    } catch (NoSuchMethodException nsme) {
        // invalid main or not FX application, abort with an error
        abort(null, "java.launcher.cls.error4", mainClass.getName(),
              FXHelper.JAVAFX_APPLICATION_CLASS_NAME);
        return; // Avoid compiler issues
    }

    /*
     * getMethod (above) will choose the correct method, based
     * on its name and parameter type, however, we still have to
     * ensure that the method is static and returns a void.
     */
    int mod = mainMethod.getModifiers();
    if (!Modifier.isStatic(mod)) {
        abort(null, "java.launcher.cls.error2", "static",
              mainMethod.getDeclaringClass().getName());
    }
    if (mainMethod.getReturnType() != java.lang.Void.TYPE) {
        abort(null, "java.launcher.cls.error3",
              mainMethod.getDeclaringClass().getName());
    }
}
 
Example 7
Project: OpenJSharp   File: ObjectStreamClass.java   View Source Code Vote up 6 votes
/**
 * Returns non-static private method with given signature defined by given
 * class, or null if none found.  Access checks are disabled on the
 * returned method (if any).
 */
private static Method getPrivateMethod(Class<?> cl, String name,
                                       Class<?>[] argTypes,
                                       Class<?> returnType)
{
    try {
        Method meth = cl.getDeclaredMethod(name, argTypes);
        meth.setAccessible(true);
        int mods = meth.getModifiers();
        return ((meth.getReturnType() == returnType) &&
                ((mods & Modifier.STATIC) == 0) &&
                ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 8
Project: MystiCraft   File: CommandManager.java   View Source Code Vote up 5 votes
public void register(Object obj) {
	for (Method m : obj.getClass().getMethods()) {
		if (!Modifier.isStatic(m.getModifiers()) && m.getParameterCount() == 1
				&& m.getParameterTypes()[0] == CommandContext.class) {
			if (m.isAnnotationPresent(Command.class) && m.getReturnType() == boolean.class) {
				registerCommand(m, obj);
			} else if (m.isAnnotationPresent(Completer.class) && m.getReturnType() == List.class) {
				registerCompleter(m, obj);
			}
		}
	}
}
 
Example 9
Project: incubator-netbeans   File: Stub.java   View Source Code Vote up 5 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class[] paramTypes = method.getParameterTypes();

    if ("hashCode".equals(methodName)) {
        return new Integer(System.identityHashCode(proxy));
    } else if ("equals".equals(methodName) && paramTypes.length == 1 && paramTypes[0] == Object.class) {
        return Boolean.valueOf(args[0] == proxy);
    }
        
    Class retClass = method.getReturnType();
    
    if (retClass.isPrimitive()) {
        if (retClass == Byte.TYPE) {
            return new Byte((byte)0);
        } else if (retClass == Short.TYPE) {
            return new Short((short)0);
        } else if (retClass == Integer.TYPE) {
            return new Integer(0);
        } else if (retClass == Long.TYPE) {
            return new Long(0L);
        } else if (retClass == Float.TYPE) {
            return new Float(0);
        } else if (retClass == Double.TYPE) {
            return new Double(0.0);
        } else if (retClass == Character.TYPE) {
            return new Character('\0');
        } else if (retClass == Boolean.TYPE) {
            return Boolean.FALSE;
        }
    }
        
    return null;
}
 
Example 10
Project: GitHub   File: TypeIT.java   View Source Code Vote up 5 votes
@Test
public void typeExtendsJavaClassWithGenerics() throws NoSuchMethodException {
    Method getterMethod = classWithManyTypes.getMethod("getTypeWithInheritedClassWithGenerics");

    final Class<?> generatedClass = getterMethod.getReturnType();
    assertThat(generatedClass.getName(), is("com.example.TypeWithInheritedClassWithGenerics"));
    assertThat(generatedClass.getSuperclass().equals(InheritedClassWithGenerics.class), equalTo(true));
    assertThat(((ParameterizedType) generatedClass.getGenericSuperclass()).getActualTypeArguments(), equalTo(new Type[]
            {
                    String.class, Integer.class, Boolean.class
            }));
}
 
Example 11
Project: FastMustache   File: MemberType.java   View Source Code Vote up 5 votes
public MemberType(Method method, Type clazzType) {
    this.clazz = method.getReturnType();
    this.clazzType = clazzType;

    if(clazz.isArray()) {
        component = clazz.getComponentType();
    } else {
        component = (Class<?>)((ParameterizedType)method.getGenericReturnType()).getActualTypeArguments()[0];
    }
}
 
Example 12
Project: openjdk-jdk10   File: NashornBeansLinker.java   View Source Code Vote up 5 votes
private static boolean isOverridableObjectMethod(final Method m) {
    switch (m.getName()) {
        case "equals":
            if (m.getReturnType() == boolean.class) {
                final Class<?>[] params = m.getParameterTypes();
                return params.length == 1 && params[0] == Object.class;
            }
            return false;
        case "hashCode":
            return m.getReturnType() == int.class && m.getParameterCount() == 0;
        case "toString":
            return m.getReturnType() == String.class && m.getParameterCount() == 0;
    }
    return false;
}
 
Example 13
Project: jdk8u-jdk   File: MemberName.java   View Source Code Vote up 5 votes
@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 14
Project: ats-framework   File: ClassTemplateProcessor.java   View Source Code Vote up 5 votes
private String getReturnClassImports(
                                      Class<?> actionClass ) {

    Method[] actionClassMethods = actionClass.getDeclaredMethods();
    //using TreeSet to prevent duplication of imports and have sorted list
    Set<String> imports = new TreeSet<String>();
    for (Method m : actionClassMethods) {
        if (ActionClassGenerator.isAnActionClass(m)) {

            // import method return type if needed
            Class<?> returnType = m.getReturnType();
            //check if the return type is an array
            if (returnType.getComponentType() != null) {
                returnType = returnType.getComponentType();
            }
            if (needsToImportMethodReturnType(returnType)) {
                addImport(imports, returnType, m.getGenericReturnType());
            }

            // import method parameter types if needed
            Class<?> methodParameterTypes[] = m.getParameterTypes();
            Type methodGenericParameterTypes[] = m.getGenericParameterTypes();
            for (int i = 0; i < methodParameterTypes.length; i++) {
                Class<?> methodParameterType = methodParameterTypes[i];
                if (needsToImportMethodParameterType(methodParameterType)) {
                    addImport(imports, methodParameterType, methodGenericParameterTypes[i]);
                }
            }
        }
    }
    if (imports.size() > 0) {
        StringBuilder sb = new StringBuilder();
        for (String s : imports) {
            sb.append(s);
        }
        return sb.toString();
    } else {
        return "";
    }
}
 
Example 15
Project: aws-sdk-java-v2   File: ConversionSchemas.java   View Source Code Vote up 5 votes
@Override
public ArgumentUnmarshaller getUnmarshaller(
        Method getter,
        Method setter) {
    final StandardAnnotationMaps.FieldMap<?> annotations = StandardAnnotationMaps.of(getter, null);
    final DynamoDbMarshalling marshalling = annotations.actualOf(DynamoDbMarshalling.class);
    if (marshalling != null) {
        return new CustomUnmarshaller(getter.getReturnType(), marshalling.marshallerClass());
    }
    return wrapped.getUnmarshaller(getter, setter);
}
 
Example 16
Project: jdk8u-jdk   File: ProxyGenerator.java   View Source Code Vote up 5 votes
/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class<?> fromClass) {
    String name = m.getName();
    Class<?>[] parameterTypes = m.getParameterTypes();
    Class<?> returnType = m.getReturnType();
    Class<?>[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class<?>[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}
 
Example 17
Project: boohee_v5.6   File: FieldInfo.java   View Source Code Vote up 4 votes
public FieldInfo(String name, Method method, Field field, Class<?> clazz, Type type, int ordinal, int serialzeFeatures) {
    Class<?> fieldClass;
    Type fieldType;
    Type genericFieldType;
    this.ordinal = 0;
    this.getOnly = false;
    this.name = name;
    this.method = method;
    this.field = field;
    this.ordinal = ordinal;
    this.serialzeFeatures = serialzeFeatures;
    if (method != null) {
        TypeUtils.setAccessible(method);
    }
    if (field != null) {
        TypeUtils.setAccessible(field);
    }
    if (method != null) {
        if (method.getParameterTypes().length == 1) {
            fieldClass = method.getParameterTypes()[0];
            fieldType = method.getGenericParameterTypes()[0];
        } else {
            fieldClass = method.getReturnType();
            fieldType = method.getGenericReturnType();
            this.getOnly = true;
        }
        this.declaringClass = method.getDeclaringClass();
    } else {
        fieldClass = field.getType();
        fieldType = field.getGenericType();
        this.declaringClass = field.getDeclaringClass();
    }
    if (clazz != null && fieldClass == Object.class && (fieldType instanceof TypeVariable)) {
        genericFieldType = getInheritGenericType(clazz, (TypeVariable) fieldType);
        if (genericFieldType != null) {
            this.fieldClass = TypeUtils.getClass(genericFieldType);
            this.fieldType = genericFieldType;
            return;
        }
    }
    genericFieldType = getFieldType(clazz, type, fieldType);
    if (genericFieldType != fieldType) {
        if (genericFieldType instanceof ParameterizedType) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        } else if (genericFieldType instanceof Class) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        }
    }
    this.fieldType = genericFieldType;
    this.fieldClass = fieldClass;
}
 
Example 18
Project: openjdk-jdk10   File: NameAndSignature.java   View Source Code Vote up 4 votes
NameAndSignature(Method m) {
    this.name = m.getName();
    this.returnType = m.getReturnType();
    this.parameterTypes = m.getParameterTypes();
}
 
Example 19
Project: monarch   File: MBeanProxyInvocationHandler.java   View Source Code Vote up 4 votes
/**
 * 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.isTraceEnabled()) {
    logger.trace("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 delegateToFucntionService(objectName, methodName, args, signature);

  }

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

}
 
Example 20
Project: openjdk-jdk10   File: CheckOverrides.java   View Source Code Vote up 4 votes
MethodSignature(Method method) {
    this(method.getReturnType(), method.getName(), method.getParameterTypes());
}