Java Code Examples for java.lang.reflect.Method#getReturnType()
The following examples show how to use
java.lang.reflect.Method#getReturnType() .
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: Introspector.java From openjdk-jdk9 with GNU General Public License v2.0 | 8 votes |
/** * Returns {@code true} if the given method is a "getter" method (where * "getter" method is a public method of the form getXXX or "boolean * isXXX") */ static boolean isReadMethod(Method method) { // ignore static methods int modifiers = method.getModifiers(); if (Modifier.isStatic(modifiers)) return false; String name = method.getName(); Class<?>[] paramTypes = method.getParameterTypes(); int paramCount = paramTypes.length; if (paramCount == 0 && name.length() > 2) { // boolean isXXX() if (name.startsWith(IS_METHOD_PREFIX)) return (method.getReturnType() == boolean.class); // getXXX() if (name.length() > 3 && name.startsWith(GET_METHOD_PREFIX)) return (method.getReturnType() != void.class); } return false; }
Example 2
Source File: ReflectivelyDiscoveredSteps.java From selenium with Apache License 2.0 | 6 votes |
private static Object getExpectedValue(Method method, String locator, String value) { Class<?> returnType = method.getReturnType(); if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { return true; } switch (method.getParameterCount()) { case 0: return locator; case 1: return value; default: throw new SeleniumException("Unable to find expected result: " + method.getName()); } }
Example 3
Source File: ResultBeanResponseProcessor.java From http-api-invoker with MIT License | 6 votes |
/** * 支持泛型的反序列化方法 */ private Object parseObject(Method method, String dataString) { if (dataString == null || dataString.trim().isEmpty()) { return null; } // 方法无需返回值 Class<?> returnType = method.getReturnType(); if (returnType == Void.class || returnType == void.class) { return null; } else if (returnType == Object.class || returnType == String.class || method.getReturnType() == CharSequence.class) { return dataString; } return JSON.parseObject(dataString, method.getGenericReturnType()); }
Example 4
Source File: XmlSerializationTester.java From SNOMED-in-5-minutes with Apache License 2.0 | 5 votes |
/** * Tests XML and JSON serialization for equality,. * * @return true, if successful * @throws Exception the exception */ public boolean testXmlSerialization() throws Exception { Logger.getLogger(getClass()).debug( "Test xml serialization - " + clazz.getName()); Object obj = createObject(1); Logger.getLogger(getClass()).debug(obj); String xml = Utility.getStringForGraph(obj); Logger.getLogger(getClass()).debug("xml = " + xml); Object obj2 = Utility.getGraphForString(xml, obj.getClass()); String json = Utility.getJsonForGraph(obj); Logger.getLogger(getClass()).debug("json = " + json); Object obj3 = Utility.getGraphForJson(json, obj.getClass()); Logger.getLogger(getClass()).debug(obj); Logger.getLogger(getClass()).debug(obj2); Logger.getLogger(getClass()).debug(obj3); // If obj has an "id" field, compare the ids try { final Method method = obj.getClass().getMethod("getId", new Class<?>[] {}); if (method != null && method.getReturnType() == Long.class) { final Long id1 = (Long) method.invoke(obj, new Object[] {}); final Long id2 = (Long) method.invoke(obj2, new Object[] {}); final Long id3 = (Long) method.invoke(obj3, new Object[] {}); if (!id1.equals(id2) || !id2.equals(id3)) { Logger.getLogger(getClass()).debug( " id fields do not match " + id1 + ", " + id2 + ", " + id3); return false; } } } catch (NoSuchMethodException e) { // this is OK } return obj.equals(obj2) && obj.equals(obj3); }
Example 5
Source File: Reflect.java From star-zone-android with Apache License 2.0 | 5 votes |
/** * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } }
Example 6
Source File: JavaNameResolver.java From anno4j with Apache License 2.0 | 5 votes |
public boolean isAnnotationOfClasses(URI name) { Method m = roles.findAnnotationMethod(name); if (m == null) return false; Class<?> type = m.getReturnType(); return type.equals(Class.class) || type.getComponentType() != null && type.getComponentType().equals(Class.class); }
Example 7
Source File: DefaultMXBeanMappingFactory.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static String propertyName(Method m) { String rest = null; String name = m.getName(); if (name.startsWith("get")) rest = name.substring(3); else if (name.startsWith("is") && m.getReturnType() == boolean.class) rest = name.substring(2); if (rest == null || rest.length() == 0 || m.getParameterTypes().length > 0 || m.getReturnType() == void.class || name.equals("getClass")) return null; return rest; }
Example 8
Source File: ResourceUtils.java From cxf with Apache License 2.0 | 5 votes |
private static void evaluateResourceMethod(ClassResourceInfo cri, boolean enableStatic, MethodDispatcher md, Method m, Method annotatedMethod) { String httpMethod = AnnotationUtils.getHttpMethodValue(annotatedMethod); Path path = AnnotationUtils.getMethodAnnotation(annotatedMethod, Path.class); if (httpMethod != null || path != null) { if (!checkAsyncResponse(annotatedMethod)) { return; } md.bind(createOperationInfo(m, annotatedMethod, cri, path, httpMethod), m); if (httpMethod == null) { // subresource locator Class<?> subClass = m.getReturnType(); if (subClass == Class.class) { subClass = InjectionUtils.getActualType(m.getGenericReturnType()); } if (enableStatic) { ClassResourceInfo subCri = cri.findResource(subClass, subClass); if (subCri == null) { ClassResourceInfo ancestor = getAncestorWithSameServiceClass(cri, subClass); subCri = ancestor != null ? ancestor : createClassResourceInfo(subClass, subClass, cri, false, enableStatic, cri.getBus()); } if (subCri != null) { cri.addSubClassResourceInfo(subCri); } } } } else { reportInvalidResourceMethod(m, NOT_RESOURCE_METHOD_MESSAGE_ID, Level.FINE); } }
Example 9
Source File: ReflectUtils.java From dubbox-hystrix with Apache License 2.0 | 5 votes |
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 10
Source File: DefaultMXBeanMappingFactory.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static String propertyName(Method m) { String rest = null; String name = m.getName(); if (name.startsWith("get")) rest = name.substring(3); else if (name.startsWith("is") && m.getReturnType() == boolean.class) rest = name.substring(2); if (rest == null || rest.length() == 0 || m.getParameterTypes().length > 0 || m.getReturnType() == void.class || name.equals("getClass")) return null; return rest; }
Example 11
Source File: LauncherHelper.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
static void validateMainClass(Class<?> mainClass) { Method mainMethod = null; 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(), JAVAFX_APPLICATION_CLASS_NAME); } catch (Throwable e) { if (mainClass.getModule().isNamed()) { abort(e, "java.launcher.module.error5", mainClass.getName(), mainClass.getModule(), e.getClass().getName(), e.getLocalizedMessage()); } else { abort(e, "java.launcher.cls.error7", mainClass.getName(), e.getClass().getName(), e.getLocalizedMessage()); } } /* * 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 12
Source File: ManageChannelProxy.java From faster-framework-project with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) { String methodName = method.getName(); String className = method.getDeclaringClass().getName(); if ("toString".equals(methodName) && args.length == 0) { return className + "@" + invoker.hashCode(); } else if ("hashCode".equals(methodName) && args.length == 0) { return invoker.hashCode(); } else if ("equals".equals(methodName) && args.length == 1) { Object another = Utils.safeElement(args, 0); return proxy == another; } String annotationMethodName = method.getAnnotation(GRpcMethod.class).value(); MethodCallProperty methodCallProperty = callDefinitions.get(StringUtils.isEmpty(annotationMethodName) ? methodName : annotationMethodName); ClientCall<Object, Object> clientCall = buildCall(methodCallProperty); switch (methodCallProperty.getMethodType()) { case UNARY: if (method.getReturnType() == ListenableFuture.class) { //等于ClientCalls.futureUnaryCall() return ClientCalls.futureUnaryCall(clientCall, Utils.safeElement(args, 0)); } else if (method.getReturnType().getName().equals("void")) { //等于ClientCalls.asyncUnaryCall(); if (Utils.checkMethodHasParamClass(method, StreamObserver.class)) { ClientCalls.asyncUnaryCall(clientCall, Utils.safeElement(args, 0), (StreamObserver<Object>) Utils.safeElement(args, 1)); return null; } else { ClientCalls.blockingUnaryCall(clientCall, Utils.safeElement(args, 0)); return null; } } return ClientCalls.blockingUnaryCall(clientCall, Utils.safeElement(args, 0)); case BIDI_STREAMING://双向流,相当于asyncBidiStreamingCall //获取返回类型的泛型 return ClientCalls.asyncBidiStreamingCall(clientCall, (StreamObserver<Object>) Utils.safeElement(args, 0)); case CLIENT_STREAMING: //客户端流。等于ClientCalls.asyncClientStreamingCall() return ClientCalls.asyncClientStreamingCall(clientCall, (StreamObserver<Object>) Utils.safeElement(args, 0)); case SERVER_STREAMING://等于ClientCalls.blockingServerStreamingCall return ClientCalls.blockingServerStreamingCall(clientCall, Utils.safeElement(args, 0)); } return null; }
Example 13
Source File: OneToManyAnnotationHandler.java From minnal with Apache License 2.0 | 5 votes |
@Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { Class<?> elementType = getElementType(method.getGenericReturnType()); CollectionMetaData collectionMetaData = new CollectionMetaData(metaData.getEntityClass(), getGetterName(method, false), elementType, method.getReturnType(), isEntity(elementType)); metaData.addCollection(collectionMetaData); }
Example 14
Source File: ReflectUtil.java From flowable-engine with Apache License 2.0 | 5 votes |
public static boolean isSetter(Method method, boolean allowBuilderPattern) { String name = method.getName(); Class<?> type = method.getReturnType(); Class<?> params[] = method.getParameterTypes(); if (!SETTER_PATTERN.matcher(name).matches()) { return false; } return params.length == 1 && (type.equals(Void.TYPE) || (allowBuilderPattern && method.getDeclaringClass().isAssignableFrom(type))); }
Example 15
Source File: AstProperty.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { Object base = prefix.eval(bindings, context); if (base == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", prefix)); } Object property = getProperty(bindings, context); if (property == null && strict) { throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base)); } String name = bindings.convert(property, String.class); Method method = findMethod(name, base.getClass(), returnType, paramTypes); return new MethodInfo(method.getName(), method.getReturnType(), paramTypes); }
Example 16
Source File: RuntimeModeler.java From hottub with GNU General Public License v2.0 | 4 votes |
/** * models the exceptions thrown by <code>method</code> and adds them to the <code>javaMethod</code> * runtime model object * @param javaMethod the runtime model object to add the exception model objects to * @param method the <code>method</code> from which to find the exceptions to model */ protected void processExceptions(JavaMethodImpl javaMethod, Method method) { Action actionAnn = getAnnotation(method, Action.class); FaultAction[] faultActions = {}; if(actionAnn != null) faultActions = actionAnn.fault(); for (Class<?> exception : method.getExceptionTypes()) { //Exclude RuntimeException, RemoteException and Error etc if (!EXCEPTION_CLASS.isAssignableFrom(exception)) continue; if (RUNTIME_EXCEPTION_CLASS.isAssignableFrom(exception) || REMOTE_EXCEPTION_CLASS.isAssignableFrom(exception)) continue; Class exceptionBean; Annotation[] anns; WebFault webFault = getAnnotation(exception, WebFault.class); Method faultInfoMethod = getWSDLExceptionFaultInfo(exception); ExceptionType exceptionType = ExceptionType.WSDLException; String namespace = targetNamespace; String name = exception.getSimpleName(); String beanPackage = packageName + PD_JAXWS_PACKAGE_PD; if (packageName.length() == 0) beanPackage = JAXWS_PACKAGE_PD; String className = beanPackage+ name + BEAN; String messageName = exception.getSimpleName(); if (webFault != null) { if (webFault.faultBean().length()>0) className = webFault.faultBean(); if (webFault.name().length()>0) name = webFault.name(); if (webFault.targetNamespace().length()>0) namespace = webFault.targetNamespace(); if (webFault.messageName().length()>0) messageName = webFault.messageName(); } if (faultInfoMethod == null) { exceptionBean = getExceptionBeanClass(className, exception, name, namespace); exceptionType = ExceptionType.UserDefined; anns = getAnnotations(exceptionBean); } else { exceptionBean = faultInfoMethod.getReturnType(); anns = getAnnotations(faultInfoMethod); } QName faultName = new QName(namespace, name); TypeInfo typeRef = new TypeInfo(faultName, exceptionBean, anns); CheckedExceptionImpl checkedException = new CheckedExceptionImpl(javaMethod, exception, typeRef, exceptionType); checkedException.setMessageName(messageName); for(FaultAction fa: faultActions) { if(fa.className().equals(exception) && !fa.value().equals("")) { checkedException.setFaultAction(fa.value()); break; } } javaMethod.addException(checkedException); } }
Example 17
Source File: EqualsHashcodeTester.java From SNOMED-in-5-minutes with Apache License 2.0 | 4 votes |
/** * Creates two objects and verifies that any difference in identity fields * produces inequality. * * @return true, if successful * @throws Exception the exception */ public boolean testIdentityFieldNotEquals() throws Exception { Logger.getLogger(getClass()).debug( "Test identity field not equals - " + clazz.getName()); // Create an object Object o1 = createObject(1); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { /* We're looking for single-argument setters. */ Method m = methods[i]; if (!m.getName().startsWith("set")) continue; String fieldName = m.getName().substring(3); Class<?>[] args = m.getParameterTypes(); if (args.length != 1) continue; /* Check the field name against our include/exclude list. */ if (includes != null && !includes.contains(fieldName.toLowerCase())) continue; if (excludes.contains(fieldName.toLowerCase())) continue; /* Is there a getter that returns the same type? */ Method getter; try { getter = clazz.getMethod("get" + fieldName, new Class[] {}); if (getter.getReturnType() != args[0]) continue; } catch (NoSuchMethodException e) { try { getter = clazz.getMethod("is" + fieldName, new Class[] {}); if (getter.getReturnType() != args[0]) continue; } catch (NoSuchMethodException e2) { continue; } } // Create second object each time, so we can compare resetting each field // value Object o2 = createObject(1); // Change the field (use an initializer of 2). setField(o2, getter, m, args[0], 2); if (o1.equals(o2)) { // if equals, fail here Logger.getLogger(getClass()).debug( " o1 = " + o1.hashCode() + ", " + o1); Logger.getLogger(getClass()).debug( " o2 = " + o2.hashCode() + ", " + o2); throw new Exception("Equality did not change when field " + fieldName + " was changed"); } } return true; }
Example 18
Source File: MethodGetter.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
public MethodGetter(Method m) { method = m; type = m.getReturnType(); }
Example 19
Source File: ReflectUtils.java From saluki with Apache License 2.0 | 4 votes |
public static Class<?> getTypeOfRep(Method method) { return method.getReturnType(); }
Example 20
Source File: ClassFieldAccessorFactory.java From kogito-runtimes with Apache License 2.0 | 4 votes |
/** * Creates the proxy reader method for the given method */ protected static void buildGetMethod(final Class< ? > originalClass, final String className, final Class< ? > superClass, final Method getterMethod, final ClassWriter cw) { final Class< ? > fieldType = getterMethod.getReturnType(); Method overridingMethod; try { overridingMethod = superClass.getMethod( getOverridingGetMethodName( fieldType ), InternalWorkingMemory.class, Object.class ); } catch ( final Exception e ) { throw new RuntimeException( "This is a bug. Please report back to JBoss Rules team.", e ); } final MethodVisitor mv = cw.visitMethod( Opcodes.ACC_PUBLIC, overridingMethod.getName(), Type.getMethodDescriptor( overridingMethod ), null, null ); mv.visitCode(); final Label l0 = new Label(); mv.visitLabel( l0 ); mv.visitVarInsn( Opcodes.ALOAD, 2 ); mv.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( originalClass ) ); if ( originalClass.isInterface() ) { mv.visitMethodInsn( Opcodes.INVOKEINTERFACE, Type.getInternalName( originalClass ), getterMethod.getName(), Type.getMethodDescriptor( getterMethod ), true); } else { mv.visitMethodInsn( Opcodes.INVOKEVIRTUAL, Type.getInternalName( originalClass ), getterMethod.getName(), Type.getMethodDescriptor( getterMethod ), false); } mv.visitInsn( Type.getType( fieldType ).getOpcode( Opcodes.IRETURN ) ); final Label l1 = new Label(); mv.visitLabel( l1 ); mv.visitLocalVariable( "this", "L" + className + ";", null, l0, l1, 0 ); mv.visitLocalVariable( "workingMemory", Type.getDescriptor( InternalWorkingMemory.class ), null, l0, l1, 1 ); mv.visitLocalVariable( "object", Type.getDescriptor( Object.class ), null, l0, l1, 2 ); mv.visitMaxs( 0, 0 ); mv.visitEnd(); }