Java 类java.lang.reflect.Method 实例源码

项目:SmartRefresh    文件:RefreshContentWrapper.java   
@Override
public AnimatorUpdateListener onLoadingFinish(int footerHeight, Interpolator interpolator, int duration) {
    if (mScrollableView != null) {
        if (mScrollableView instanceof RecyclerView) ((RecyclerView) mScrollableView).smoothScrollBy(0, footerHeight, interpolator);
        else if (mScrollableView instanceof ScrollView) ((ScrollView) mScrollableView).smoothScrollBy(0, footerHeight);
        else if (mScrollableView instanceof AbsListView) ((AbsListView) mScrollableView).smoothScrollBy(footerHeight, duration);
        else {
            try {
                Method method = mScrollableView.getClass().getDeclaredMethod("smoothScrollBy", Integer.class, Integer.class);
                method.invoke(mScrollableView, 0, footerHeight);
            } catch (Exception e) {
                int scrollX = mScrollableView.getScrollX();
                int scrollY = mScrollableView.getScrollY();
                return animation -> mScrollableView.scrollTo(scrollX, scrollY + (int) animation.getAnimatedValue());
            }
        }
        return null;
    }
    return null;
}
项目:aws-sdk-java-v2    文件:XpathUtils.java   
/**
 * Used to optimize performance by avoiding expensive file access every time
 * a DTMManager is constructed as a result of constructing a Xalan xpath
 * context!
 */
private static void speedUpDtmManager() throws Exception {
    // https://github.com/aws/aws-sdk-java/issues/238
    // http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance
    // CHECKSTYLE:OFF - We need to load system properties from third-party libraries.
    if (System.getProperty(DTM_MANAGER_DEFAULT_PROP_NAME) == null) {
        // CHECKSTYLE:ON
        Class<?> xPathContextClass = Class.forName(XPATH_CONTEXT_CLASS_NAME);
        Method getDtmManager = xPathContextClass.getMethod("getDTMManager");
        Object xPathContext = xPathContextClass.newInstance();
        Object dtmManager = getDtmManager.invoke(xPathContext);

        if (DTM_MANAGER_IMPL_CLASS_NAME.equals(dtmManager.getClass().getName())) {
            // This would avoid the file system to be accessed every time
            // the internal XPathContext is instantiated.
            System.setProperty(DTM_MANAGER_DEFAULT_PROP_NAME,
                               DTM_MANAGER_IMPL_CLASS_NAME);
        }
    }
}
项目:uroborosql    文件:DoubleArrayParameterMapperTest.java   
private static <I> I newProxy(final Class<I> interfaceType) {
    Object o = new Object();

    Method getOriginal;
    try {
        getOriginal = ProxyContainer.class.getMethod("getOriginal");
    } catch (NoSuchMethodException | SecurityException e) {
        throw new AssertionError(e);
    }

    I proxyInstance = newProxy(interfaceType, new Class<?>[] { ProxyContainer.class }, (proxy, method, args) -> {
        if (getOriginal.equals(method)) {
            return o;
        }

        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ProxyContainer) {
                args[i] = ((ProxyContainer) args[i]).getOriginal();
            }
        }
        return method.invoke(o, args);
    });
    return proxyInstance;
}
项目:springreplugin    文件:ReflectUtils.java   
public static Object invokeMethod(Method method, Object methodReceiver, Object... methodParamValues) throws
        InvocationTargetException, IllegalAccessException {

    if (method != null) {
        boolean acc = method.isAccessible();

        if (!acc) {
            method.setAccessible(true);
        }

        Object ret = method.invoke(methodReceiver, methodParamValues);

        if (!acc) {
            method.setAccessible(false);
        }

        return ret;
    }

    return null;
}
项目:marathonv5    文件:AssertionTreeView.java   
private AssertionTreeItem getTreeItemForMethod(Object object, Method method) {
    boolean accessible = method.isAccessible();
    try {
        method.setAccessible(true);
        Object value = method.invoke(object, new Object[] {});
        if (value != null) {
            if (value.getClass().isArray())
                value = RFXComponent.unboxPremitiveArray(value);
            return new AssertionTreeItem(value, getPropertyName(method.getName()));
        }
    } catch (Throwable t) {
    } finally {
        method.setAccessible(accessible);
    }
    return null;
}
项目:DroidPlugin    文件:IActivityManagerHookHandle.java   
@Override
protected boolean beforeInvoke(Object receiver, Method method, Object[] args) throws Throwable {
    //2.3,15,16,17,18,19,21
/* public void grantUriPermissionFromOwner(IBinder owner, int fromUid, String targetPkg,
    Uri uri, int mode) throws RemoteException;*/
    //这个函数是用来给某个包授予访问某个URI的权限。
    //插件调用这个函数会传插件自己的包名,而此插件并未被安装。就这样调用原来函数传给系统,是会出问题的。所以改成宿主程序的包名。
    final int index = 2;
    if (args != null && args.length > index) {
        if (args[index] != null && args[index] instanceof String) {
            String targetPkg = (String) args[index];
            if (isPackagePlugin(targetPkg)) {
                args[index] = mHostContext.getPackageName();
            }
        }
    }

    return super.beforeInvoke(receiver, method, args);
}
项目:jetcache    文件:CacheHandlerTest.java   
@Test
public void testStaticInvoke1() throws Throwable {
    Method method = CountClass.class.getMethod("count");
    int x1, x2, x3;
    method.invoke(count);

    x1 = invoke(method, null);
    x2 = invoke(method, null);
    x3 = invoke(method, null);
    Assert.assertEquals(x1, x2);
    Assert.assertEquals(x1, x3);

    method = CountClass.class.getMethod("count", int.class);
    int X1, X2, X3, X4;

    X1 = invoke(method, new Object[]{1000});
    X2 = invoke(method, new Object[]{2000});
    X3 = invoke(method, new Object[]{1000});
    X4 = invoke(method, new Object[]{2000});
    Assert.assertEquals(X1, X3);
    Assert.assertEquals(X2, X4);

}
项目:apache-tomcat-7.0.73-with-comment    文件:ApplicationContextFacade.java   
/**
 * Executes the method of the specified <code>ApplicationContext</code>
 * @param method The method object to be invoked.
 * @param context The AppliationContext object on which the method
 *                   will be invoked
 * @param params The arguments passed to the called method.
 */
private Object executeMethod(final Method method, 
                             final ApplicationContext context,
                             final Object[] params) 
        throws PrivilegedActionException, 
               IllegalAccessException,
               InvocationTargetException {

    if (SecurityUtil.isPackageProtectionEnabled()){
       return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
            @Override
            public Object run() throws IllegalAccessException, InvocationTargetException{
                return method.invoke(context,  params);
            }
        });
    } else {
        return method.invoke(context, params);
    }        
}
项目:jdk8u-jdk    文件:BasicComboBoxEditor.java   
public Object getItem() {
    Object newValue = editor.getText();

    if (oldValue != null && !(oldValue instanceof String))  {
        // The original value is not a string. Should return the value in it's
        // original type.
        if (newValue.equals(oldValue.toString()))  {
            return oldValue;
        } else {
            // Must take the value from the editor and get the value and cast it to the new type.
            Class<?> cls = oldValue.getClass();
            try {
                Method method = MethodUtil.getMethod(cls, "valueOf", new Class[]{String.class});
                newValue = MethodUtil.invoke(method, oldValue, new Object[] { editor.getText()});
            } catch (Exception ex) {
                // Fail silently and return the newValue (a String object)
            }
        }
    }
    return newValue;
}
项目:Jupiter    文件:SimpleCommandMap.java   
@Override
public void registerSimpleCommands(Object object) {
    for (Method method : object.getClass().getDeclaredMethods()) {
        cn.nukkit.command.simple.Command def = method.getAnnotation(cn.nukkit.command.simple.Command.class);
        if (def != null) {
            SimpleCommand sc = new SimpleCommand(object, method, def.name(), def.description(), def.usageMessage(), def.aliases());

            Arguments args = method.getAnnotation(Arguments.class);
            if (args != null) {
                sc.setMaxArgs(args.max());
                sc.setMinArgs(args.min());
            }

            CommandPermission perm = method.getAnnotation(CommandPermission.class);
            if (perm != null) {
                sc.setPermission(perm.value());
            }

            if (method.isAnnotationPresent(ForbidConsole.class)) {
                sc.setForbidConsole(true);
            }

            this.register(def.name(), sc);
        }
    }
}
项目:Zxing    文件:FlashlightManager.java   
private static Method maybeGetMethod(Class<?> clazz, String name, Class<?>... argClasses)
{
    try
    {
        return clazz.getMethod(name, argClasses);
    }
    catch (NoSuchMethodException nsme)
    {
        // OK
        return null;
    }
    catch (RuntimeException re)
    {
        Log.w(TAG, "Unexpected error while finding method " + name, re);
        return null;
    }
}
项目:vertx-zero    文件:Flower.java   
private static WebException verifyPureArguments(
        final Validator verifier,
        final Depot depot,
        final Object[] args) {
    final Event event = depot.getEvent();
    final Object proxy = event.getProxy();
    final Method method = event.getAction();
    WebException error = null;
    try {
        if (Virtual.is(proxy)) {
            // TODO: Wait for proxy generation
            // Validation for dynamic proxy
            // final Object delegate = Instance.getProxy(method);
            // verifier.verifyMethod(delegate, method, args);
        } else {
            // Validation for proxy
            verifier.verifyMethod(proxy, method, args);
        }
    } catch (final WebException ex) {
        // Basic validation failure
        error = ex;
    }
    return error;
}
项目:hibernateMaster    文件:DomainUtil.java   
@SuppressWarnings("unchecked")
public static Method getIDmethod(Class<? extends BaseDomain> clazz) {
    if (clazz.getAnnotation(IdClass.class) != null) {
        try {
            return clazz.getDeclaredMethod("getDomainID");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("含有"+IdClass.class.getName()+
                    "的domain必须实现"+UnionKeyDomain.class.getName()+"接口!!!",e);
        }
    }

    Method[] methods = clazz.getDeclaredMethods();
    for (Method m:methods) {
        Annotation aa = m.getAnnotation(Id.class);
        if (aa == null) {
            continue;
        }
        return m;
    }
    if (clazz == BaseDomain.class) {
        return null;
    }
    return getIDmethod((Class<? extends BaseDomain>)clazz.getSuperclass());
}
项目:sql-streams-spring    文件:SqlStreamTransactionAwareProxy.java   
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
    Sql sql = this.sql;

    if (method.getDeclaringClass() == SqlStreamHolder.class) {
        return sql;
    }

    TransactionStatus transactionStatus = null;
    try {
        transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    } catch (NoTransactionException e) {
        if (FAIL_WITHOUT_TRANSACTION) {
            throw e;
        }
    }
    if (transactionStatus instanceof SqlStreamTransactionStatus) {
        sql = ((SqlStreamTransactionStatus) transactionStatus).transaction;
    }

    return method.invoke(sql, objects);
}
项目:apache-tomcat-7.0.73-with-comment    文件:StatementDecoratorInterceptor.java   
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("getStatement")) {
        return this.st;
    } else {
        try {
            return method.invoke(this.delegate, args);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException
                    && t.getCause() != null) {
                throw t.getCause();
            } else {
                throw t;
            }
        }
    }
}
项目:rent    文件:ApplicationContextListener.java   
@Override
 public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
     // root application context
     if(null == contextRefreshedEvent.getApplicationContext().getParent()) {
         logger.debug(">>>>> spring初始化完毕 <<<<<");
         // spring初始化完毕后,通过反射调用所有使用BaseService注解的initMapper方法
         Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class);
         for(Map.Entry<String, Object> entry : baseServices.entrySet()){
    System.out.println(entry.getKey() + "," + entry.getValue());
}
         for(Object service : baseServices.values()) {
             logger.debug(">>>>> {}.initMapper()", service.getClass().getName());
             try {
                 Method initMapper = service.getClass().getMethod("initMapper");
                 initMapper.invoke(service);
             } catch (Exception e) {
                 logger.error("初始化BaseService的initMapper方法异常", e);
                 e.printStackTrace();
             }
         }
     }
 }
项目:drinkwater-java    文件:TraceRouteBuilder.java   
public static ProcessorDefinition addServerReceivedTracing(IDrinkWaterService service,
                                                       RouteDefinition routeDefinition,
                                                       Method method) {
    ProcessorDefinition answer = routeDefinition;
    if (!service.getConfiguration().getIsTraceEnabled()) {
        return answer;
    }

    answer = routeDefinition
            .setHeader(BeanOperationName)
            .constant(Operation.of(method))
            .to(ROUTE_serverReceivedEvent);


    return answer;
}
项目:jdk8u-jdk    文件:FullscreenEnterEventTest.java   
private static void enableFullScreen(Window window) {
    try {
        Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
        Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
        setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
        Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
        Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                switch (method.getName()) {
                    case "windowEnteringFullScreen":
                        windowEnteringFullScreen = true;
                        break;
                    case "windowEnteredFullScreen":
                        windowEnteredFullScreen = true;
                        break;
                }
                return null;
            }
        });
        Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
        addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
    } catch (Exception e) {
        throw new RuntimeException("FullScreen utilities not available", e);
    }
}
项目:OpenJSharp    文件:StandardMBeanIntrospector.java   
static boolean isDefinitelyImmutableInfo(Class<?> implClass) {
    if (!NotificationBroadcaster.class.isAssignableFrom(implClass))
        return true;
    synchronized (definitelyImmutable) {
        Boolean immutable = definitelyImmutable.get(implClass);
        if (immutable == null) {
            final Class<NotificationBroadcasterSupport> nbs =
                    NotificationBroadcasterSupport.class;
            if (nbs.isAssignableFrom(implClass)) {
                try {
                    Method m = implClass.getMethod("getNotificationInfo");
                    immutable = (m.getDeclaringClass() == nbs);
                } catch (Exception e) {
                    // Too bad, we'll say no for now.
                    return false;
                }
            } else
                immutable = false;
            definitelyImmutable.put(implClass, immutable);
        }
        return immutable;
    }
}
项目:openjdk-jdk10    文件:KerberosTixDateTest.java   
private static void testDestroy(KerberosTicket t) throws Exception {
    t.destroy();
    if (!t.isDestroyed()) {
        throw new RuntimeException("ticket should have been destroyed");
    }
    // Although these methods are meaningless, they can be called
    for (Method m: KerberosTicket.class.getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers())
                && m.getParameterCount() == 0) {
            System.out.println("Testing " + m.getName() + "...");
            try {
                m.invoke(t);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RefreshFailedException ||
                        cause instanceof IllegalStateException) {
                    // this is OK
                } else {
                    throw e;
                }
            }
        }
    }
    System.out.println("Destroy Test Passed");
}
项目:lams    文件:MBeanClientInterceptor.java   
/**
 * Routes a method invocation (not a property get/set) to the corresponding
 * operation on the managed resource.
 * @param method the method corresponding to operation on the managed resource.
 * @param args the invocation arguments
 * @return the value returned by the method invocation.
 */
private Object invokeOperation(Method method, Object[] args) throws JMException, IOException {
    MethodCacheKey key = new MethodCacheKey(method.getName(), method.getParameterTypes());
    MBeanOperationInfo info = this.allowedOperations.get(key);
    if (info == null) {
        throw new InvalidInvocationException("Operation '" + method.getName() +
                "' is not exposed on the management interface");
    }
    String[] signature = null;
    synchronized (this.signatureCache) {
        signature = this.signatureCache.get(method);
        if (signature == null) {
            signature = JmxUtils.getMethodSignature(method);
            this.signatureCache.put(method, signature);
        }
    }
    return this.serverToUse.invoke(this.objectName, method.getName(), args, signature);
}
项目:amv-access-api-poc    文件:Clients.java   
@Override
public HystrixCommand.Setter create(Target<?> target, Method method) {
    String groupKey = target.name();
    String commandKey = Feign.configKey(target.type(), method);

    HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter()
            .withCoreSize(DEFAULT_THREAD_POOL_SIZE);

    HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
            .withFallbackEnabled(false)
            .withExecutionTimeoutEnabled(true)
            .withExecutionTimeoutInMilliseconds(DEFAULT_TIMEOUT_IN_MS)
            .withExecutionIsolationStrategy(THREAD)
            .withExecutionIsolationThreadInterruptOnTimeout(true);

    return HystrixCommand.Setter
            .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
            .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
            .andThreadPoolPropertiesDefaults(threadPoolProperties)
            .andCommandPropertiesDefaults(commandProperties);
}
项目:Accessibility    文件:SDCardUtils.java   
private static String getStorageVolumeStats(Object service, Object storageVolume, String path) {
    try {
        Class<? extends Object> StorageVolumeClass = storageVolume.getClass();
        Method getState = StorageVolumeClass.getMethod("getState");
        return (String) getState.invoke(storageVolume);
    } catch (Exception e) {
        try {
            Class IMountService = service.getClass();
            Method getVolumeState = IMountService.getMethod("getVolumeState", String.class);
            return (String) getVolumeState.invoke(service, path);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    return Environment.MEDIA_UNMOUNTABLE;
}
项目:OpenJSharp    文件:EventHandler.java   
private Object applyGetters(Object target, String getters) {
    if (getters == null || getters.equals("")) {
        return target;
    }
    int firstDot = getters.indexOf('.');
    if (firstDot == -1) {
        firstDot = getters.length();
    }
    String first = getters.substring(0, firstDot);
    String rest = getters.substring(Math.min(firstDot + 1, getters.length()));

    try {
        Method getter = null;
        if (target != null) {
            getter = Statement.getMethod(target.getClass(),
                                  "get" + NameGenerator.capitalize(first),
                                  new Class<?>[]{});
            if (getter == null) {
                getter = Statement.getMethod(target.getClass(),
                               "is" + NameGenerator.capitalize(first),
                               new Class<?>[]{});
            }
            if (getter == null) {
                getter = Statement.getMethod(target.getClass(), first, new Class<?>[]{});
            }
        }
        if (getter == null) {
            throw new RuntimeException("No method called: " + first +
                                       " defined on " + target);
        }
        Object newTarget = MethodUtil.invoke(getter, target, new Object[]{});
        return applyGetters(newTarget, rest);
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to call method: " + first +
                                   " on " + target, e);
    }
}
项目:homunculus    文件:SPRControllerEndpoint.java   
@Nullable
@Override
public AnnotatedMethod process(Method method) {
    RequestMapping named = method.getAnnotation(RequestMapping.class);
    if (named != null) {
        Class[] parameterTypes = Reflection.getParameterTypes(method);
        String[] parameterNames = new String[parameterTypes.length];
        String name = "";
        if (named.value().length > 0) {
            name = named.value()[0];
        } else {
            name = method.getName();
        }
        AnnotatedMethod res = new AnnotatedMethod(method, name, parameterTypes, parameterNames);
        Annotation[][] declaredParameterAnnotations = Reflection.getParameterAnnotations(method);
        NEXT_PARAM:
        for (int i = 0; i < declaredParameterAnnotations.length; i++) {
            Annotation[] annotations = declaredParameterAnnotations[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof RequestParam) {
                    String pName = ((RequestParam) annotation).value();
                    parameterNames[i] = pName;
                    continue NEXT_PARAM;
                }
            }
            //if we come here, no annotation was found -> not good!
            LoggerFactory.getLogger(method.getDeclaringClass()).error("{}.{}: {}. Parameter is unnamed and may cause invocation failure at runtime ", method.getDeclaringClass().getSimpleName(), res, i);
        }
        return res;
    }
    return null;
}
项目:Simplify-Core    文件:TemporalCodec.java   
@Override
public Object parse(Object o, Method m) {
    Class<?> parameterTypes = getParameterTypes(m);
    if (LocalDate.class == parameterTypes) {
        return LocalDate.parse(o.toString());
    } else if (LocalDateTime.class == parameterTypes) {
        return LocalDateTime.parse(o.toString(), DateTimeFormatterExt.ISO_LOCAL_DATE_TIME);
    } else if (LocalTime.class == parameterTypes) {
        return LocalTime.parse(o.toString());
    }
    return null;
}
项目:OpenJSharp    文件:AquaUtilControlSize.java   
private static void applyUISizing(final JComponent c, final Size size) {
    try {
        // see if this component has a "getUI" method
        final Class<? extends JComponent> clazz = c.getClass();
        final Method getUIMethod = clazz.getMethod("getUI", new Class[0]);

        // see if that UI is one of ours that understands sizing
        final Object ui = getUIMethod.invoke(c, new Object[0]);
        if (!(ui instanceof Sizeable)) return;

        // size it!
        final Sizeable sizeable = (Sizeable)ui;
        sizeable.applySizeFor(c, size);
    } catch (final Throwable e) { return; }
}
项目:pub-service    文件:ReflectionUtil.java   
/**
 * 将po对象中有属性和值转换成map
 * 
 * @param po
 * @return
 */
public static Map po2Map(Object po) {
    Map poMap = new HashMap();
    Map map = new HashMap();
    try {
        map = BeanUtils.describe(po);
    } catch (Exception ex) {
    }
    Object[] keyArray = map.keySet().toArray();
    for (int i = 0; i < keyArray.length; i++) {
        String str = keyArray[i].toString();
        if (str != null && !str.equals("class")) {
            if (map.get(str) != null) {
                poMap.put(str, map.get(str));
            }
        }
    }

    Method[] ms =po.getClass().getMethods();
    for(Method m:ms){
        String name = m.getName();

        if(name.startsWith("get")||name.startsWith("is")){
            if(m.getAnnotation(NotDbField.class)!=null||m.getAnnotation(PrimaryKeyField.class)!=null){
                poMap.remove(getFieldName(name)); 
            } 
        }

    }

    /**
     * 如果此实体为动态字段实体,将动态字段加入
     */
    if(po instanceof DynamicField){
        DynamicField dynamicField = (DynamicField) po;
        Map fields = dynamicField.getFields();
        poMap.putAll(fields);
    }
    return poMap;
}
项目:CSipSimple    文件:SearchView.java   
private static void ensureImeVisible(AutoCompleteTextView view, boolean visible) {
    try {
        Method method = AutoCompleteTextView.class.getMethod("ensureImeVisible", boolean.class);
        method.setAccessible(true);
        method.invoke(view, visible);
    } catch (Exception e) {
        //Oh well...
    }
}
项目:enigma-vk    文件:ConstInfoAccessor.java   
@Override
public String toString() {
    try {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        PrintWriter out = new PrintWriter(buf);
        Method print = m_item.getClass().getMethod("print", PrintWriter.class);
        print.setAccessible(true);
        print.invoke(m_item, out);
        out.close();
        return buf.toString().replace("\n", "");
    } catch (Exception ex) {
        throw new Error(ex);
    }
}
项目:promagent    文件:Delegator.java   
private static boolean methodNameAndNumArgsMatch(Method interceptedMethod, HookMetadata.MethodSignature instrumentedMethod) {
    if (!interceptedMethod.getName().equals(instrumentedMethod.getMethodName())) {
        return false;
    }
    if (interceptedMethod.getParameterCount() != instrumentedMethod.getParameterTypes().size()) {
        return false;
    }
    return true;
}
项目:openjdk-jdk10    文件:RemoteObjectInvocationHandler.java   
/**
 * Handles java.lang.Object methods.
 **/
private Object invokeObjectMethod(Object proxy,
                                  Method method,
                                  Object[] args)
{
    String name = method.getName();

    if (name.equals("hashCode")) {
        return hashCode();

    } else if (name.equals("equals")) {
        Object obj = args[0];
        InvocationHandler hdlr;
        return
            proxy == obj ||
            (obj != null &&
             Proxy.isProxyClass(obj.getClass()) &&
             (hdlr = Proxy.getInvocationHandler(obj)) instanceof RemoteObjectInvocationHandler &&
             this.equals(hdlr));

    } else if (name.equals("toString")) {
        return proxyToString(proxy);

    } else {
        throw new IllegalArgumentException(
            "unexpected Object method: " + method);
    }
}
项目:zheng-lite    文件:BaseServiceImpl.java   
@Override
public List<Record> selectByExampleWithBLOBsForStartPage(Example example, Integer pageNum, Integer pageSize) {
    try {
        DynamicDataSource.setDataSource(DataSourceEnum.SLAVE.getName());
        Method selectByExampleWithBLOBs = mapper.getClass().getDeclaredMethod("selectByExampleWithBLOBs", example.getClass());
        PageHelper.startPage(pageNum, pageSize, false);
        Object result = selectByExampleWithBLOBs.invoke(mapper, example);
        return (List<Record>) result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    DynamicDataSource.clearDataSource();
    return null;
}
项目:KBUnitTest    文件:InsertOrReplaceProxy.java   
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

    if (method.getName().equals("toString") && args.length == 0) {
        String sql = toString((String) proxy.invoke(realInsert, args));
        return sql;
    }
    return proxy.invoke(realInsert, args);
}
项目:JavaGraph    文件:Operator.java   
/**
 * Returns the method from a given signature class with a given name.
 * This method is supposed to implement an operator, and should therefore be
 * declared exactly once, as a public abstract method.
 */
private static Method getOperatorMethod(Class<?> sigClass, java.lang.String name) {
    Method result = null;
    java.lang.String className = sigClass.getSimpleName();
    java.lang.String sigName = className.substring(0, className.indexOf("Signature"))
        .toLowerCase();
    Method[] methods = sigClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName()
            .equals(name)) {
            if (result != null) {
                throw new IllegalArgumentException(java.lang.String
                    .format("Operator overloading for '%s:%s' not allowed", sigName, name));
            }
            result = method;
        }
    }
    if (result == null) {
        throw new IllegalArgumentException(
            java.lang.String.format("No method found for operator '%s:%s'", sigName, name));
    }
    if (!Modifier.isAbstract(result.getModifiers())) {
        throw new IllegalArgumentException(java.lang.String
            .format("Method for operator '%s:%s' should be abstract", sigName, name));
    }
    if (!Modifier.isPublic(result.getModifiers())) {
        throw new IllegalArgumentException(java.lang.String
            .format("Method for operator '%s:%s' should be public", sigName, name));
    }
    return result;
}
项目:ats-framework    文件:Test_AtsDataProvider.java   
/**
 * @throws NoSuchMethodException
 * @throws DataProviderException
 * @throws ConfigurationException 
 * @throws NoSuchPropertyException 
 * 
 */
@Test( expected = DataProviderException.class)
public void verifyProviderNegativeNoSheetInExcel() throws NoSuchMethodException, DataProviderException,
                                                   NoSuchPropertyException, ConfigurationException {

    Method testMethod = findMethodByNameOnly(ExcelProviderTest.class, "wrong");
    AtsDataProvider.getTestData(testMethod);
}
项目:NotifyTools    文件:MethodDescriptor.java   
/**
 * <p>
 * Constructs an instance with the given {@link Method}. The
 * {@link #getName()} is set as the name of the <code>method</code>
 * passed.
 * </p>
 * 
 * @param method
 *            The Method to set.
 */
public MethodDescriptor(Method method) {
    super();

    if (method == null) {
        throw new NullPointerException();
    }
    this.method = method;

    setName(method.getName());
}
项目:jdk8u-jdk    文件:BasicFunctionality.java   
public static void testProvider() throws Exception {

       // These just shouldn't throw any exeptions:
       bp.plainProbe();
       bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L));
       bp.probeWithArgs(42, (float)3.14, null, null);
       bp.probeWithName();
       bp.overloadedProbe();
       bp.overloadedProbe(42);

       Method m = BasicProvider.class.getMethod("plainProbe");
       Probe p = bp.getProbe(m);
       if (p == null) {
           fail("Provider.getProbe: Did not return probe");
       }

       Method m2 = BasicFunctionality.class.getMethod("testProvider");
       p = bp.getProbe(m2);
       if (p != null) {
           fail("Provider.getProbe: Got probe with invalid spec");
       }

       bp.dispose();
       // These just shouldn't throw any exeptions:
       bp.plainProbe();
       bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L));
       bp.probeWithArgs(42, (float)3.14, null, null);
       bp.probeWithName();
       bp.overloadedProbe();
       bp.overloadedProbe(42);

       if (bp.getProbe(m) != null) {
           fail("Provider.getProbe: Should return null after dispose()");
       }

       bp.dispose(); // just to make sure nothing bad happens
    }
项目:OpenJSharp    文件:RuntimeModeler.java   
private Class getRequestWrapperClass(String className, Method method, QName reqElemName) {
    ClassLoader loader =  (classLoader == null) ? Thread.currentThread().getContextClassLoader() : classLoader;
    try {
        return loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        if (noWrapperGen()) return WrapperComposite.class;
        logger.fine("Dynamically creating request wrapper Class " + className);
        return WrapperBeanGenerator.createRequestWrapperBean(className, method, reqElemName, loader);
    }
}
项目:ProyectoPacientes    文件:CachedRowsetTest.java   
/**
 * Tests fix for BUG#5188, CachedRowSet errors using PreparedStatement. Uses
 * Sun's "com.sun.rowset.CachedRowSetImpl"
 * 
 * @throws Exception
 */
public void testBug5188() throws Exception {
    String implClass = "com.sun.rowset.CachedRowSetImpl";
    Class<?> c;
    Method populate;
    try {
        c = Class.forName(implClass);
    } catch (ClassNotFoundException e) {
        System.out.println("skipping testBug5188. Requires: " + implClass);
        return;
    }
    populate = c.getMethod("populate", new Class[] { ResultSet.class });

    createTable("testBug5188", "(ID int NOT NULL AUTO_INCREMENT, datafield VARCHAR(64), PRIMARY KEY(ID))");

    this.stmt.executeUpdate("INSERT INTO testBug5188(datafield) values('test data stuff !')");

    String sql = "SELECT * FROM testBug5188 where ID = ?";
    this.pstmt = this.conn.prepareStatement(sql);
    this.pstmt.setString(1, "1");
    this.rs = this.pstmt.executeQuery();

    // create a CachedRowSet and populate it
    RowSet cachedRowSet = (RowSet) c.newInstance();
    // cachedRowSet.populate(rs);
    populate.invoke(cachedRowSet, new Object[] { this.rs });

    // scroll through CachedRowSet ...
    assertTrue(cachedRowSet.next());
    assertEquals("1", cachedRowSet.getString("ID"));
    assertEquals("test data stuff !", cachedRowSet.getString("datafield"));
    assertFalse(cachedRowSet.next());

}