Java Code Examples for java.lang.reflect.Method#getName()
The following examples show how to use
java.lang.reflect.Method#getName() .
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: ProviderWrapper.java From joynr with Apache License 2.0 | 6 votes |
private Method getMethodFromInterfaces(Class<?> beanClass, Method method, boolean isProviderMethod) throws NoSuchMethodException { String name = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); Method result = method; if (!isProviderMethod) { result = null; for (Class<?> interfaceClass : beanClass.getInterfaces()) { try { if ((result = interfaceClass.getMethod(name, parameterTypes)) != null) { break; } } catch (NoSuchMethodException | SecurityException e) { if (logger.isTraceEnabled()) { logger.trace(format("Method %s not found on interface %s", name, interfaceClass)); } } } } return result == null ? method : result; }
Example 2
Source File: PipelineOptionsReflector.java From beam with Apache License 2.0 | 6 votes |
/** * Extract pipeline options and their respective getter methods from a series of {@link Method * methods}. A single pipeline option may appear in many methods. * * @return A mapping of option name to the input methods which declare it. */ static Multimap<String, Method> getPropertyNamesToGetters(Iterable<Method> methods) { Multimap<String, Method> propertyNamesToGetters = HashMultimap.create(); for (Method method : methods) { String methodName = method.getName(); if ((!methodName.startsWith("get") && !methodName.startsWith("is")) || method.getParameterTypes().length != 0 || method.getReturnType() == void.class) { continue; } String propertyName = Introspector.decapitalize( methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3)); propertyNamesToGetters.put(propertyName, method); } return propertyNamesToGetters; }
Example 3
Source File: InvocationMatcher.java From astor with GNU General Public License v2.0 | 6 votes |
public boolean hasSameMethod(Invocation candidate) { //not using method.equals() for 1 good reason: //sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); if (m1.getName() != null && m1.getName().equals(m2.getName())) { /* Avoid unnecessary cloning */ Class[] params1 = m1.getParameterTypes(); Class[] params2 = m2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } } return false; }
Example 4
Source File: CodeBuilder.java From anno4j with Apache License 2.0 | 6 votes |
public CodeBuilder insert(Method method) { Class<?> declaringClass = method.getDeclaringClass(); String name = method.getName(); Class<?>[] params = method.getParameterTypes(); CodeBuilder cb = klass.getCodeBuilder(); String var = cb.methodVars.get(method); if (var == null) { var = cb.getVarName("Method"); } else { body.append(var); return this; } String before = toString(); clear(); String parameterTypes = declareVar(params, cb); CodeBuilder field = klass.assignStaticField(Method.class, var); field.insert(declaringClass); field.code(".getDeclaredMethod(").insert(name); field.code(", ").code(parameterTypes).code(")").end(); cb.methodVars.put(method, var); code(before); body.append(var); return this; }
Example 5
Source File: PublishAllBeanWrapper.java From simplejmx with ISC License | 6 votes |
public JmxOperationInfo[] getOperationInfos() { List<JmxOperationInfo> operationInfos = new ArrayList<JmxOperationInfo>(); Set<String> knownMethods = new HashSet<String>(); for (Class<?> clazz = target.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { for (Method method : clazz.getMethods()) { if (!knownMethods.add(method.getName())) { continue; } String name = method.getName(); if (!ignoredMethods.contains(name) && !isGetAttributeMethod(name)) { operationInfos.add(new JmxOperationInfo(name, null, null, OperationAction.UNKNOWN, null)); } } } return operationInfos.toArray(new JmxOperationInfo[operationInfos.size()]); }
Example 6
Source File: ReflectUtil.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Check if the given method is a method declared in the proxy interface * implemented by the given proxy instance. * * @param proxy a proxy instance * @param method an interface method dispatched to a InvocationHandler * * @throws IllegalArgumentException if the given proxy or method is invalid. */ public static void checkProxyMethod(Object proxy, Method method) { // check if it is a valid proxy instance if (proxy == null || !Proxy.isProxyClass(proxy.getClass())) { throw new IllegalArgumentException("Not a Proxy instance"); } if (Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException("Can't handle static method"); } Class<?> c = method.getDeclaringClass(); if (c == Object.class) { String name = method.getName(); if (name.equals("hashCode") || name.equals("equals") || name.equals("toString")) { return; } } if (isSuperInterface(proxy.getClass(), c)) { return; } // disallow any method not declared in one of the proxy intefaces throw new IllegalArgumentException("Can't handle: " + method); }
Example 7
Source File: DynamoDBEntityMetadataSupport.java From spring-data-dynamodb with Apache License 2.0 | 5 votes |
protected String getPropertyNameForAccessorMethod(Method method) { String methodName = method.getName(); String propertyName = null; if (methodName.startsWith("get")) { propertyName = methodName.substring(3); } else if (methodName.startsWith("is")) { propertyName = methodName.substring(2); } Assert.notNull(propertyName, "Hash or range key annotated accessor methods must start with 'get' or 'is'"); String firstLetter = propertyName.substring(0, 1); String remainder = propertyName.substring(1); return firstLetter.toLowerCase() + remainder; }
Example 8
Source File: CmdValidator.java From rocketmq with Apache License 2.0 | 5 votes |
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); if (clazz.isAnnotationPresent(Service.class)) { Method[] methodArr = clazz.getDeclaredMethods(); for (Method method : methodArr) { if (method.isAnnotationPresent(CmdTrace.class)) { CmdTrace cmdTrace = method.getAnnotation(CmdTrace.class); Class<? extends SubCommand> cmdClazz = cmdTrace.cmdClazz(); String methodName = clazz.getSimpleName() + "." + method.getName(); if (method2cmd.get(methodName) == null) { method2cmd.put(methodName, cmdClazz); } else { throw new IllegalStateException(methodName + " = {" + method2cmd.get(methodName).getName() + "," + cmdClazz.getName() + "}"); } if (cmd2method.get(cmdClazz) == null) { cmd2method.put(cmdClazz, methodName); } else { throw new IllegalStateException(cmdClazz + " = {" + cmd2method.get(cmdClazz) + "," + methodName + "}"); } } } } return bean; }
Example 9
Source File: ReflectionHelper.java From cm_ext with Apache License 2.0 | 5 votes |
/** * Returns the name of the property associated with the getter method. * If the method is not a a getter, an IllegalStateException is thrown. * * @param method the method. * @return the property name. */ public static String propertyNameOfGetter(Method method) { Preconditions.checkNotNull(method); String name = method.getName(); for (String prefix : GETTER_PREFIXES) { if (name.startsWith(prefix)) { return Introspector.decapitalize(name.substring(prefix.length())); } } throw new IllegalStateException("Method is malformed " + method.getName()); }
Example 10
Source File: MethodHelper.java From qaf with MIT License | 5 votes |
private static String calculateMethodCanonicalName(Method m) { String result = CANONICAL_NAME_CACHE.get(m); if (result != null) { return result; } String packageName = m.getDeclaringClass().getName() + "." + m.getName(); // Try to find the method on this class or parents Class<?> cls = m.getDeclaringClass(); while (cls != Object.class) { try { if (cls.getDeclaredMethod(m.getName(), m.getParameterTypes()) != null) { packageName = cls.getName(); break; } } catch (Exception e) { // ignore } cls = cls.getSuperclass(); } result = packageName + "." + m.getName(); CANONICAL_NAME_CACHE.put(m, result); return result; }
Example 11
Source File: CglibProxyFactory.java From mybaties with Apache License 2.0 | 5 votes |
@Override public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { final String methodName = method.getName(); try { synchronized (lazyLoader) { if (WRITE_REPLACE_METHOD.equals(methodName)) { Object original = null; if (constructorArgTypes.isEmpty()) { original = objectFactory.create(type); } else { original = objectFactory.create(type, constructorArgTypes, constructorArgs); } PropertyCopier.copyBeanProperties(type, enhanced, original); if (lazyLoader.size() > 0) { return new CglibSerialStateHolder(original, lazyLoader.getProperties(), objectFactory, constructorArgTypes, constructorArgs); } else { return original; } } else { //这里是关键,延迟加载就是调用ResultLoaderMap.loadAll() if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) { if (aggressive || lazyLoadTriggerMethods.contains(methodName)) { lazyLoader.loadAll(); } else if (PropertyNamer.isProperty(methodName)) { //或者调用ResultLoaderMap.load() final String property = PropertyNamer.methodToProperty(methodName); if (lazyLoader.hasLoader(property)) { lazyLoader.load(property); } } } } } return methodProxy.invokeSuper(enhanced, args); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } }
Example 12
Source File: DefaultCommandManager.java From kyoko with MIT License | 5 votes |
private void registerCommand(Command command) { if (command == null) return; var disabled = Settings.instance().disabledCommands(); if (disabled != null && !disabled.isEmpty() && disabled.contains(command.getName())) { return; } var aliases = List.of(command.getAliases()); for (Method method : command.getClass().getMethods()) { try { if (method.isAnnotationPresent(SubCommand.class) && method.getParameterCount() == 1) { var subCommand = method.getAnnotation(SubCommand.class); var handle = MethodHandles.lookup().bind(command, method.getName(), contextType); String name = subCommand.name().isEmpty() ? method.getName() : subCommand.name(); command.getSubCommands().put(name.toLowerCase(), handle); logger.debug("Registered subcommand: {} -> {}", name, method); for (String alias : subCommand.aliases()) { command.getSubCommands().put(alias.toLowerCase(), handle); logger.debug("Registered subcommand: {} -> {}", alias, method); } } } catch (Exception e) { logger.error("Error while registering subcommand!", e); } } registered.add(command); commands.put(command.getName().toLowerCase(), command); aliases.forEach(alias -> commands.put(alias, command)); command.onRegister(); logger.debug("Registered command: {} -> {}", command.getName(), command); }
Example 13
Source File: ClassFieldInspector.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private void addToMapping( final Method method, final int index ) { final String name = method.getName(); int offset; if ( name.startsWith( "is" ) ) { offset = 2; } else if ( name.startsWith( "get" ) || name.startsWith( "set" ) ) { offset = 3; } else { offset = 0; } final String fieldName = calcFieldName( name, offset ); if ( this.fieldNames.containsKey( fieldName ) ) { //only want it once, the first one thats found if ( offset != 0 && this.nonGetters.contains( fieldName ) ) { //replace the non getter method with the getter one Integer oldIndex = removeOldField( fieldName ); storeField( oldIndex, fieldName ); storeGetterSetter( method, fieldName ); this.nonGetters.remove( fieldName ); } else if ( offset != 0 ) { storeGetterSetter( method, fieldName ); } } else { storeField( index, fieldName ); storeGetterSetter( method, fieldName ); if ( offset == 0 ) { // only if it is a non-standard getter method this.nonGetters.add( fieldName ); } } }
Example 14
Source File: AnnotationMetadataReadingVisitor.java From thinking-in-spring-boot-samples with Apache License 2.0 | 5 votes |
public AnnotationVisitor visitAnnotation(final String desc, boolean visible) { final String className = Type.getType(desc).getClassName(); final Map<String, Object> attributes = new LinkedHashMap<String, Object>(); return new EmptyVisitor() { public void visit(String name, Object value) { // Explicitly defined annotation attribute value. attributes.put(name, value); } public void visitEnd() { try { Class annotationClass = classLoader.loadClass(className); // Check declared default values of attributes in the annotation type. Method[] annotationAttributes = annotationClass.getMethods(); for (int i = 0; i < annotationAttributes.length; i++) { Method annotationAttribute = annotationAttributes[i]; String attributeName = annotationAttribute.getName(); Object defaultValue = annotationAttribute.getDefaultValue(); if (defaultValue != null && !attributes.containsKey(attributeName)) { attributes.put(attributeName, defaultValue); } } // Register annotations that the annotation type is annotated with. Annotation[] metaAnnotations = annotationClass.getAnnotations(); Set<String> metaAnnotationTypeNames = new HashSet<String>(); for (Annotation metaAnnotation : metaAnnotations) { metaAnnotationTypeNames.add(metaAnnotation.annotationType().getName()); } metaAnnotationMap.put(className, metaAnnotationTypeNames); } catch (ClassNotFoundException ex) { // Class not found - can't determine meta-annotations. } attributesMap.put(className, attributes); } }; }
Example 15
Source File: PipelineOptionsFactory.java From beam with Apache License 2.0 | 4 votes |
/** * This method is meant to emulate the behavior of {@link Introspector#getBeanInfo(Class, int)} to * construct the list of {@link PropertyDescriptor}. * * <p>TODO: Swap back to using Introspector once the proxy class issue with AppEngine is resolved. */ private static List<PropertyDescriptor> getPropertyDescriptors( Set<Method> methods, Class<? extends PipelineOptions> beanClass) throws IntrospectionException { SortedMap<String, Method> propertyNamesToGetters = new TreeMap<>(); for (Map.Entry<String, Method> entry : PipelineOptionsReflector.getPropertyNamesToGetters(methods).entries()) { propertyNamesToGetters.put(entry.getKey(), entry.getValue()); } List<PropertyDescriptor> descriptors = Lists.newArrayList(); List<TypeMismatch> mismatches = new ArrayList<>(); Set<String> usedDescriptors = Sets.newHashSet(); /* * Add all the getter/setter pairs to the list of descriptors removing the getter once * it has been paired up. */ for (Method method : methods) { String methodName = method.getName(); if (!methodName.startsWith("set") || method.getParameterTypes().length != 1 || method.getReturnType() != void.class) { continue; } String propertyName = Introspector.decapitalize(methodName.substring(3)); Method getterMethod = propertyNamesToGetters.remove(propertyName); // Validate that the getter and setter property types are the same. if (getterMethod != null) { Type getterPropertyType = getterMethod.getGenericReturnType(); Type setterPropertyType = method.getGenericParameterTypes()[0]; if (!getterPropertyType.equals(setterPropertyType)) { TypeMismatch mismatch = new TypeMismatch(); mismatch.propertyName = propertyName; mismatch.getterPropertyType = getterPropertyType; mismatch.setterPropertyType = setterPropertyType; mismatches.add(mismatch); continue; } } // Properties can appear multiple times with subclasses, and we don't // want to add a bad entry if we have already added a good one (with both // getter and setter). if (!usedDescriptors.contains(propertyName)) { descriptors.add(new PropertyDescriptor(propertyName, getterMethod, method)); usedDescriptors.add(propertyName); } } throwForTypeMismatches(mismatches); // Add the remaining getters with missing setters. for (Map.Entry<String, Method> getterToMethod : propertyNamesToGetters.entrySet()) { descriptors.add( new PropertyDescriptor(getterToMethod.getKey(), getterToMethod.getValue(), null)); } return descriptors; }
Example 16
Source File: SetTopRuleProvider.java From lams with GNU General Public License v2.0 | 4 votes |
/** * {@inheritDoc} */ public void init(SetTop annotation, Method element) { this.methodName = element.getName(); this.paramType = element.getParameterTypes()[0].getName(); }
Example 17
Source File: MapOverrideTest.java From attic-polygene-java with Apache License 2.0 | 4 votes |
public ReadOnlyException( Composite me, Method method ) { super( "Method " + method.getName() + " in [" + me.toString() + "] is READ ONLY." ); }
Example 18
Source File: MBeanServerInvocationHandler.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
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 19
Source File: ClassGeneratorVault.java From baratine with GNU General Public License v2.0 | 4 votes |
private void createConstructor(JavaClass jClass, String superClassName) { JavaMethod ctor = jClass.createMethod("<init>", void.class, VaultDriver.class); ctor.setAccessFlags(Modifier.PUBLIC); CodeWriterAttribute code = ctor.createCodeWriter(); code.setMaxLocals(4); code.setMaxStack(10); code.pushObjectVar(0); code.invokespecial(superClassName, "<init>", void.class); //code.pushObjectVar(0); //code.pushObjectVar(1); for (Method method : _methodList) { String methodName = method.getName(); jClass.createField(fieldName(method), MethodVault.class) .setAccessFlags(Modifier.PRIVATE); code.pushObjectVar(0); code.pushObjectVar(1); /* code.pushObjectVar(0); code.invoke(Object.class, "getClass", Class.class); */ code.pushConstantClass(_type); code.pushConstant(methodName); Class<?> []paramTypes = MethodAmp.paramTypes(method); code.pushInt(paramTypes.length); code.newObjectArray(Class.class); for (int i = 0; i < paramTypes.length; i++) { code.dup(); code.pushInt(i); code.pushConstantClass(paramTypes[i]); code.setArrayObject(); } code.invokeInterface(VaultDriver.class, "newMethod", MethodVault.class, Class.class, String.class, Class[].class); code.putField(jClass.getThisClass(), fieldName(method), MethodVault.class); } //code.pushObjectVar(0); code.addReturn(); code.close(); }
Example 20
Source File: WindupAdjacencyMethodHandler.java From windup with Eclipse Public License 1.0 | 4 votes |
@Override public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) { final java.lang.reflect.Parameter[] arguments = method.getParameters(); if (ReflectionUtility.isAddMethod(method)) if (arguments == null || arguments.length == 0) return this.addVertexDefault(builder, method, annotation); else if (arguments.length == 1) if (ClassInitializer.class.isAssignableFrom(arguments[0].getType())) return this.addVertexByTypeUntypedEdge(builder, method, annotation); else return this.addVertexByObjectUntypedEdge(builder, method, annotation); else if (arguments.length == 2) { if (!(ClassInitializer.class.isAssignableFrom(arguments[1].getType()))) throw new IllegalStateException(method.getName() + " was annotated with @Adjacency, had two arguments, but the second argument was not of the type ClassInitializer"); if (ClassInitializer.class.isAssignableFrom(arguments[0].getType())) return this.addVertexByTypeTypedEdge(builder, method, annotation); else return this.addVertexByObjectTypedEdge(builder, method, annotation); } else throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but had more than 1 arguments."); else if (ReflectionUtility.isGetMethod(method)) if (arguments == null || arguments.length == 0) { if( ReflectionUtility.returnsIterator(method) ) return this.getVertexesIteratorDefault(builder, method, annotation); else if( ReflectionUtility.returnsList(method) ) return this.getVertexesListDefault(builder, method, annotation); else if( ReflectionUtility.returnsSet(method) ) return this.getVertexesSetDefault(builder, method, annotation); return this.getVertexDefault(builder, method, annotation); } else if (arguments.length == 1) { if (!(Class.class.isAssignableFrom(arguments[0].getType()))) throw new IllegalStateException(method.getName() + " was annotated with @Adjacency, had a single argument, but that argument was not of the type Class"); if (ReflectionUtility.returnsIterator(method)) return this.getVertexesIteratorByType(builder, method, annotation); else if( ReflectionUtility.returnsList(method) ) return this.getVertexesListByType(builder, method, annotation); else if( ReflectionUtility.returnsSet(method) ) return this.getVertexesSetByType(builder, method, annotation); return this.getVertexByType(builder, method, annotation); } else throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but had more than 1 arguments."); else if (ReflectionUtility.isRemoveMethod(method)) if (arguments == null || arguments.length == 0) return this.removeAll(builder, method, annotation); else if (arguments.length == 1) return this.removeVertex(builder, method, annotation); else throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but had more than 1 arguments."); else if (ReflectionUtility.isSetMethod(method)) if (arguments == null || arguments.length == 0) throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but had no arguments."); else if (arguments.length == 1) { if (ReflectionUtility.acceptsIterator(method, 0)) return this.setVertexIterator(builder, method, annotation); else if (ReflectionUtility.acceptsIterable(method, 0)) return this.setVertexIterable(builder, method, annotation); else if (ReflectionUtility.acceptsVertexFrame(method, 0)) return this.setVertexVertexFrame(builder, method, annotation); throw new IllegalStateException(method.getName() + " was annotated with @Adjacency, had a single argument, but that argument was not of the type Iterator or Iterable"); } else throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but had more than 1 arguments."); else throw new IllegalStateException(method.getName() + " was annotated with @Adjacency but did not begin with either of the following keywords: add, get, remove"); }