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

The following are Jave code examples for showing how to use getName() 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: lams   File: AutowireUtils.java   View Source Code Vote up 6 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	String methodName = method.getName();
	if (methodName.equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (methodName.equals("hashCode")) {
		// Use hashCode of proxy.
		return System.identityHashCode(proxy);
	}
	else if (methodName.equals("toString")) {
		return this.objectFactory.toString();
	}
	try {
		return method.invoke(this.objectFactory.getObject(), args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example 2
Project: hadoop-oss   File: WritableRpcEngine.java   View Source Code Vote up 6 votes
public Invocation(Method method, Object[] parameters) {
  this.methodName = method.getName();
  this.parameterClasses = method.getParameterTypes();
  this.parameters = parameters;
  rpcVersion = writableRpcVersion;
  if (method.getDeclaringClass().equals(VersionedProtocol.class)) {
    //VersionedProtocol is exempted from version check.
    clientVersion = 0;
    clientMethodsHash = 0;
  } else {
    this.clientVersion = RPC.getProtocolVersion(method.getDeclaringClass());
    this.clientMethodsHash = ProtocolSignature.getFingerprint(method
        .getDeclaringClass().getMethods());
  }
  this.declaringClassProtocolName = 
      RPC.getProtocolName(method.getDeclaringClass());
}
 
Example 3
Project: hadoop   File: HamletGen.java   View Source Code Vote up 6 votes
void genNewElementMethod(String className, Method method, int indent) {
  String methodName = method.getName();
  String retName = method.getReturnType().getSimpleName();
  Class<?>[] params = method.getParameterTypes();
  echo(indent, "\n",
       "@Override\n",
       "public ", retName, "<", className, topMode ? "> " : "<T>> ",
       methodName, "(");
  if (params.length == 0) {
    puts(0, ") {");
    puts(indent,
         topMode ? "" : "  closeAttrs();\n",
         "  return ", StringUtils.toLowerCase(retName), "_" + "(this, ",
         isInline(className, retName), ");\n", "}");
  } else if (params.length == 1) {
    puts(0, "String selector) {");
    puts(indent,
         "  return setSelector(", methodName, "(), selector);\n", "}");
  } else {
    throwUnhandled(className, method);
  }
}
 
Example 4
Project: OpenJSharp   File: MBeanServerInvocationHandler.java   View Source Code Vote up 6 votes
private static boolean isLocal(Object proxy, Method method) {
    final Class<?>[] interfaces = proxy.getClass().getInterfaces();
    if(interfaces == null) {
        return true;
    }

    final String methodName = method.getName();
    final Class<?>[] params = method.getParameterTypes();
    for (Class<?> intf : interfaces) {
        try {
            intf.getMethod(methodName, params);
            return false; // found method in one of our interfaces
        } catch (NoSuchMethodException nsme) {
            // OK.
        }
    }

    return true;  // did not find in any interface
}
 
Example 5
Project: hadoop   File: MutableMetricsFactory.java   View Source Code Vote up 5 votes
protected String getName(Method method) {
  String methodName = method.getName();
  if (methodName.startsWith("get")) {
    return StringUtils.capitalize(methodName.substring(3));
  }
  return StringUtils.capitalize(methodName);
}
 
Example 6
Project: OpenJSharp   File: IndexedPropertyDescriptor.java   View Source Code Vote up 5 votes
private void setIndexedReadMethod0(Method readMethod) {
    this.indexedReadMethodRef.set(readMethod);
    if (readMethod == null) {
        indexedReadMethodName = null;
        return;
    }
    setClass0(readMethod.getDeclaringClass());

    indexedReadMethodName = readMethod.getName();
    setTransient(readMethod.getAnnotation(Transient.class));
}
 
Example 7
Project: dremio-oss   File: Drill2769UnsupportedReportsUseSqlExceptionTest.java   View Source Code Vote up 5 votes
/**
 * Assembles method signature text for given method.
 */
private String makeLabel(Method method) {
  String methodLabel;
  methodLabel = jdbcIntf.getSimpleName() + "." + method.getName() + "(";
  boolean first = true;
  for (Class<?> paramType : method.getParameterTypes()) {
    if (! first) {
      methodLabel += ", ";
    }
    first = false;
    methodLabel += paramType.getSimpleName();
  }
  methodLabel += ")";
  return methodLabel;
}
 
Example 8
Project: xq_seckill_microservice   File: LogInterceptor.java   View Source Code Vote up 5 votes
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        startTime = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        sb.append(ENTER).append(methodName);

        //参数非空则打印参数
        Map<String, String[]> requestMap = request.getParameterMap();
        if (requestMap != null && !requestMap.isEmpty()) {
            sb.append("(");
            for (Map.Entry<String, String[]> entry : requestMap.entrySet()) {
                sb.append("[");
                sb.append(entry.getKey());
                sb.append("=");
                String[] valueArr = entry.getValue();
                sb.append(valueArr[0].toString());
                sb.append("]");
            }
            sb.append(")");
        }

        LOGGER.debug(sb.toString());
    }

    return true;
}
 
Example 9
Project: jdbacl   File: PooledConnectionHandler.java   View Source Code Vote up 5 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args)
		throws Throwable {
	String methodName = method.getName();
	if ("close".equals(methodName))
		this.close();
	else if ("getConnection".equals(methodName) && (args == null || args.length == 0))
		return this.getConnection();
	else if ("addConnectionEventListener".equals(methodName)) {
		this.addConnectionEventListener((ConnectionEventListener) args[0]);
		return null;
	} else if ("removeConnectionEventListener".equals(methodName)) {
		this.removeConnectionEventListener((ConnectionEventListener) args[0]);
		return null;
	} else if ("prepareStatement".equals(methodName)) {
		switch (args.length) {
			case 1: return DBUtil.prepareStatement(realConnection, (String) args[0], readOnly);
			case 2: 
				if (method.getParameterTypes()[1] == int.class)
					return DBUtil.prepareStatement(realConnection, (String) args[0], readOnly,
							(Integer) args[1], ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
				else
					break;
			case 3: return DBUtil.prepareStatement(realConnection, (String) args[0], readOnly,
					(Integer) args[1], (Integer) args[2], ResultSet.HOLD_CURSORS_OVER_COMMIT);
			case 4: return DBUtil.prepareStatement(realConnection, (String) args[0], readOnly, 
					(Integer) args[1], (Integer) args[2], (Integer) args[3]);
		}
	} else if ("createStatement".equals(methodName))
		return createStatement(method, args);
	return BeanUtil.invoke(realConnection, method, args);
}
 
Example 10
Project: jdk8u-jdk   File: RedefineMethodWithAnnotationsApp.java   View Source Code Vote up 5 votes
private static void verifyMethodParameterAnnotationsValue(
        String expectedValue) throws Exception {
    Class<RedefineMethodWithAnnotationsTarget> c =
            RedefineMethodWithAnnotationsTarget.class;
    Method method = c.getMethod("annotatedMethod", String.class);

    Annotation [][] parametersAnnotations =
            method.getParameterAnnotations();
    if (parametersAnnotations.length != 1) {
        throw new Exception("Incorrect number of parameters to method: " +
                method.getName() + "." +
                " Expected: 1," +
                " got: " + parametersAnnotations.length);
    }

    Annotation[] parameterAnnotations = parametersAnnotations[0];
    if (parameterAnnotations.length != 1) {
        throw new Exception("Incorrect number of annotations." +
                " Expected: 1" +
                ", got " + parameterAnnotations.length);
    }

    Annotation parameterAnnotation = parameterAnnotations[0];
    if (!(parameterAnnotation instanceof ParameterAnnotation)) {
        throw new Exception("Incorrect Annotation class." +
                " Expected: " + ParameterAnnotation.class.getName() +
                ", got: " + parameterAnnotation.getClass().getName());
    }

    ParameterAnnotation pa = (ParameterAnnotation)parameterAnnotation;
    String annotationValue = pa.value();
    if (!expectedValue.equals(annotationValue)) {
        throw new Exception("Incorrect parameter annotation value." +
                " Expected: " + expectedValue +
                ", got: " + annotationValue);
    }
}
 
Example 11
Project: vscrawler   File: AutoEventRegistry.java   View Source Code Vote up 4 votes
/**
 * 注册事件观察者,通过注解的事件观察者
 *
 * @param observer 观察者对象
 */
public void registerObserver(Object observer) {
    final Class<?> observerClass = observer.getClass();

    // 这个观察者的接口类,可能有多个
    Set<Class> allSupperClass = Sets.filter(allAutoEventMap.keySet(), new Predicate<Class>() {
        @Override
        @SuppressWarnings("unchecked")
        public boolean apply(Class input) {
            return input.isAssignableFrom(observerClass);
        }
    });

    if (allSupperClass.size() == 0) {
        log.warn("can not registry observer:{} , observer class must implement a event interface", observer);
        return;
    }

    Method[] declaredMethods = observerClass.getDeclaredMethods();
    for (Method method : declaredMethods) {
        String topic = "";
        if (method.getAnnotation(AutoEventHandler.class) != null) {
            AutoEventHandler autoEventHandler = method.getAnnotation(AutoEventHandler.class);
            topic = autoEventHandler.topic();
        }

        // find auto Topic
        for (Class supperClazz : allSupperClass) {
            Method[] supperClazzDeclaredMethods = supperClazz.getDeclaredMethods();
            for (Method supperClazzMethod : supperClazzDeclaredMethods) {
                if (!supperClazzMethod.getName().equals(method.getName())
                        || supperClazzMethod.getAnnotation(AutoEvent.class) == null) {
                    continue;
                }
                AutoEvent annotation = supperClazzMethod.getAnnotation(AutoEvent.class);
                String eventTopic = annotation.topic();

                if (StringUtils.isEmpty(eventTopic)) {// 父类指定过topic,那么子类必须指定topic
                    eventTopic = supperClazz.getName() + "#" + method.getName();
                }
                if (StringUtils.isEmpty(topic) || topic.equals(eventTopic)) {
                    // 注册一个topic为eventTopic的事件观察者
                    registerMethod(observer, method, eventTopic);
                }
            }
        }

    }
}
 
Example 12
Project: jsouplib   File: ClassReader.java   View Source Code Vote up 4 votes
private static List<Resource> getSetters(Map<String, Type> lookup, Class clazz, boolean includingPrivate) {
    ArrayList<Resource> setters = new ArrayList<Resource>();
    for (Method method : ReflectKit.getAllMethods(clazz, includingPrivate)) {
        Annotation[] annotations = method.getAnnotations();
        if (annotations ==null||annotations.length==0) {//排除未注解变量
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        String methodName = method.getName();
        if (methodName.length() < 4) {
            continue;
        }
        if (!methodName.startsWith("set")) {
            continue;
        }
        Type[] paramTypes = method.getGenericParameterTypes();
        if (paramTypes.length != 1) {
            continue;
        }
        if (!includingPrivate && !Modifier.isPublic(method.getParameterTypes()[0].getModifiers())) {
            continue;
        }
        if (includingPrivate) {
            method.setAccessible(true);
        }
        try {
            String fromName = translateSetterName(methodName);
            Resource resource = new Resource(clazz, lookup, paramTypes[0]);
            resource.fromNames = new String[]{fromName};
            resource.name = fromName;
            resource.method = method;
            resource.annotations = method.getAnnotations();
            setters.add(resource);
        } catch (Exception e) {
            throw new AJsoupReaderException("failed to onAttachView resource from setter: " + method, e);
        }
    }
    return setters;
}
 
Example 13
Project: ditb   File: RootDocProcessor.java   View Source Code Vote up 4 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  String methodName = method.getName();
  if (target instanceof Doc) {
    if (methodName.equals("isIncluded")) {
      Doc doc = (Doc) target;
      return !exclude(doc) && doc.isIncluded();
    }
    if (target instanceof RootDoc) {
      if (methodName.equals("classes")) {
        return filter(((RootDoc) target).classes(), ClassDoc.class);
      } else if (methodName.equals("specifiedClasses")) {
        return filter(((RootDoc) target).specifiedClasses(), ClassDoc.class);
      } else if (methodName.equals("specifiedPackages")) {
        return filter(((RootDoc) target).specifiedPackages(), PackageDoc.class);
      }
    } else if (target instanceof ClassDoc) {
      if (isFiltered(args)) {
        if (methodName.equals("methods")) {
          return filter(((ClassDoc) target).methods(true), MethodDoc.class);
        } else if (methodName.equals("fields")) {
          return filter(((ClassDoc) target).fields(true), FieldDoc.class);
        } else if (methodName.equals("innerClasses")) {
          return filter(((ClassDoc) target).innerClasses(true), ClassDoc.class);
        } else if (methodName.equals("constructors")) {
          return filter(((ClassDoc) target).constructors(true), ConstructorDoc.class);
        }
      }
    } else if (target instanceof PackageDoc) {
      if (methodName.equals("allClasses")) {
        if (isFiltered(args)) {
          return filter(((PackageDoc) target).allClasses(true), ClassDoc.class);
        } else {
          return filter(((PackageDoc) target).allClasses(), ClassDoc.class);
        }
      } else if (methodName.equals("annotationTypes")) {
        return filter(((PackageDoc) target).annotationTypes(), AnnotationTypeDoc.class);
      } else if (methodName.equals("enums")) {
        return filter(((PackageDoc) target).enums(), ClassDoc.class);
      } else if (methodName.equals("errors")) {
        return filter(((PackageDoc) target).errors(), ClassDoc.class);
      } else if (methodName.equals("exceptions")) {
        return filter(((PackageDoc) target).exceptions(), ClassDoc.class);
      } else if (methodName.equals("interfaces")) {
        return filter(((PackageDoc) target).interfaces(), ClassDoc.class);
      } else if (methodName.equals("ordinaryClasses")) {
        return filter(((PackageDoc) target).ordinaryClasses(), ClassDoc.class);
      }
    }
  }

  if (args != null) {
    if (methodName.equals("compareTo") || methodName.equals("equals")
        || methodName.equals("overrides") || methodName.equals("subclassOf")) {
      args[0] = unwrap(args[0]);
    }
  }
  try {
    return process(method.invoke(target, args), method.getReturnType());
  } catch (InvocationTargetException e) {
    throw e.getTargetException();
  }
}
 
Example 14
Project: vertx-zero   File: AnnotationRepeatException.java   View Source Code Vote up 4 votes
public AnnotationRepeatException(final Class<?> clazz,
                                 final Method method,
                                 final Class<? extends Annotation> annoCls,
                                 final int occurs) {
    super(clazz, method.getName(), "@" + annoCls.getSimpleName(), occurs);
}
 
Example 15
Project: EvoMaster   File: BooleanMethodTransformer.java   View Source Code Vote up 4 votes
private boolean replaceBooleanCalls(MethodNode mn) {

        boolean changed = false;
        ListIterator<AbstractInsnNode> iterator = mn.instructions.iterator();

        while (iterator.hasNext()) {
            AbstractInsnNode node = iterator.next();
            if (!(node instanceof MethodInsnNode)) {
                continue;
            }

            String replacementClass = Type.getInternalName(target);

            MethodInsnNode call = (MethodInsnNode) node;
            if (!call.owner.equals(replacementClass)) {
                continue;
            }

            for (Method m : getClass().getMethods()) {
                BooleanReplacement br = m.getAnnotation(BooleanReplacement.class);
                if (br == null) {
                    continue;
                }
                if (!call.name.equals(m.getName())) {
                    continue;
                }

                /*
                    Not going to look at the full method descriptor,
                    as return types in our replacements are going to
                    be different (eg from boolean to int)
                 */
                String paramDesc = getParameterDescriptor(m, false);
                String paramReduced = getParameterDescriptor(m, true);

                if ((br.replacingStatic() && call.desc.startsWith(paramDesc)) ||
                        (!br.replacingStatic() && call.desc.startsWith(paramReduced))) {

                    MethodInsnNode replacingCall = new MethodInsnNode(
                            Opcodes.INVOKESTATIC,
                            Type.getInternalName(getClass()),
                            m.getName(),
                            Type.getMethodDescriptor(m),
                            false);
                    mn.instructions.insertBefore(node, replacingCall);
                    mn.instructions.remove(node);

                    changed = true;
                    break;
                }
            }
        }

        return changed;
    }
 
Example 16
Project: dubbo2   File: BeanDeserializer.java   View Source Code Vote up 4 votes
/**
  * Creates a map of the classes fields.
  */
 protected HashMap getMethodMap(Class cl)
 {
   HashMap methodMap = new HashMap();
   
   for (; cl != null; cl = cl.getSuperclass()) {
     Method []methods = cl.getDeclaredMethods();
     
     for (int i = 0; i < methods.length; i++) {
Method method = methods[i];

if (Modifier.isStatic(method.getModifiers()))
  continue;

String name = method.getName();

if (! name.startsWith("set"))
  continue;

Class []paramTypes = method.getParameterTypes();
if (paramTypes.length != 1)
  continue;

if (! method.getReturnType().equals(void.class))
  continue;

if (findGetter(methods, name, paramTypes[0]) == null)
  continue;

// XXX: could parameterize the handler to only deal with public
try {
  method.setAccessible(true);
} catch (Throwable e) {
  e.printStackTrace();
}
   
name = name.substring(3);

int j = 0;
for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) {
}

if (j == 1)
  name = name.substring(0, j).toLowerCase() + name.substring(j);
else if (j > 1)
  name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1);


methodMap.put(name, method);
     }
   }

   return methodMap;
 }
 
Example 17
Project: jdk8u-jdk   File: StandardMBeanIntrospector.java   View Source Code Vote up 4 votes
@Override
String getName(Method m) {
    return m.getName();
}
 
Example 18
Project: InventoryAPI   File: Router.java   View Source Code Vote up 3 votes
/**
 * Calls a method of a gui instance marked with the Query annotation.
 * Methods needs to have QueryParameter parameters with the name used
 * in a query.
 * <br>Example: "/some/path?val=1&2&foo=TestValue"
 * <br>     @Query( args = {"val","foo"} )
 * <br>     private void demo(QueryParameter val, QueryParameter foo)
 * <br>     {
 * <br>         // val = ["1","2"]
 * <br>         // foo = ["TestValue"]
 * <br>     }
 *
 * @param gui      the gui
 * @param queryMap the query map
 *
 * @see QueryParameter
 * @see Query
 */
public void query( McGui gui, Map<String, QueryParameter> queryMap ) {

    //Find method with exact same arguments
    Method queryMethod = getQueryMethod( gui.getClass(), queryMap.keySet() );

    if(queryMethod==null)
        throw new InvalidRouteException( QUERY,"No private method found for query: "+queryMap.keySet().toString() );

    try {
        callQueryMethod( queryMethod, gui, queryMap );
    } catch ( Exception e ) {
        throw new InvalidRouteException( e,QUERY, "Can not call query method: " + queryMethod.getName() );
    }
}
 
Example 19
Project: openjdk-jdk10   File: MBeanOperationInfo.java   View Source Code Vote up 3 votes
/**
 * Constructs an {@code MBeanOperationInfo} object.  The
 * {@link Descriptor} of the constructed object will include
 * fields contributed by any annotations on the {@code Method}
 * object that contain the {@link DescriptorKey} meta-annotation.
 *
 * @param method The {@code java.lang.reflect.Method} object
 * describing the MBean operation.
 * @param description A human readable description of the operation.
 */
public MBeanOperationInfo(String description, Method method) {
    this(method.getName(),
         description,
         methodSignature(method),
         method.getReturnType().getName(),
         UNKNOWN,
         Introspector.descriptorForElement(method));
}
 
Example 20
Project: s-store   File: DINameSpace.java   View Source Code Vote up 2 votes
/**
 * Retrieves the fully qualified name of the given Method object. <p>
 *
 * @param m The Method object for which to retreive the fully
 *      qualified name
 * @return the fully qualified name of the specified Method object.
 */
static String getMethodFQN(Method m) {
    return m == null ? null
                     : m.getDeclaringClass().getName() + '.' + m.getName();
}