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

项目:Netherboard    文件:BPlayerBoard.java   
private void sendObjective(Objective obj, ObjectiveMode mode) {
    try {
        Object objHandle = NMS.getHandle(obj);

        Object packetObj = NMS.PACKET_OBJ.newInstance(
                objHandle,
                mode.ordinal()
        );

        NMS.sendPacket(packetObj, player);
    } catch(InstantiationException | IllegalAccessException
            | InvocationTargetException | NoSuchMethodException e) {

        LOGGER.error("Error while creating and sending objective packet. (Unsupported Minecraft version?)", e);
    }
}
项目:alfresco-repository    文件:ACLEntryVoterTest.java   
public void testBasicDenyParentAssocNode() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("testOneChildAssociationRef", new Class[] { ChildAssociationRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("ACL_PARENT.0.sys:base.Read")));

    proxyFactory.setTargetSource(new SingletonTargetSource(o));

    Object proxy = proxyFactory.getProxy();

    try
    {
        method.invoke(proxy, new Object[] { nodeService.getPrimaryParent(systemNodeRef) });
        assertNotNull(null);
    }
    catch (InvocationTargetException e)
    {

    }
}
项目:ares    文件:ReflectionManager.java   
/**
 * Maps object attributes.
 * @param type the class to reflect.
 * @param object the instance to address.
 * @param <T> the class to reflect.
 * @return the attributes mapping.
 * @throws IntrospectionException when errors in reflection.
 * @throws InvocationTargetException when errors in reflection.
 * @throws IllegalAccessException when errors in reflection.
 */
public static <T> Map<String,Object> getAttributes(Class<T> type, T object)
    throws IntrospectionException, InvocationTargetException, IllegalAccessException {
  Map<String,Object> propsmap = new HashMap<>();
  final BeanInfo beanInfo = Introspector.getBeanInfo(type);
  final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  for (PropertyDescriptor pd : propertyDescriptors) {
    if (pd.getName().equals("class")) continue;
    final Method getter = pd.getReadMethod();
    if (getter != null) {
      final String attrname = pd.getName();
      final Object attrvalue = getter.invoke(object);
      propsmap.put(attrname, attrvalue);
    }
  }
  return propsmap;
}
项目:parabuild-ci    文件:HsqlSocketFactory.java   
/**
 * Retrieves a new HsqlSocketFactory whose class
 * is determined by the implClass argument. The basic contract here
 * is that implementations constructed by this method should return
 * true upon calling isSecure() iff they actually create secure sockets.
 * There is no way to guarantee this directly here, so it is simply
 * trusted that an  implementation is secure if it returns true
 * for calls to isSecure();
 *
 * @return a new secure socket factory
 * @param implClass the fully qaulified name of the desired
 *      class to construct
 * @throws Exception if a new secure socket factory cannot
 *      be constructed
 */
private static HsqlSocketFactory newFactory(String implClass)
throws Exception {

    Class       clazz;
    Constructor ctor;
    Class[]     ctorParm;
    Object[]    ctorArg;
    Object      factory;

    clazz    = Class.forName(implClass);
    ctorParm = new Class[0];

    // protected constructor
    ctor    = clazz.getDeclaredConstructor(ctorParm);
    ctorArg = new Object[0];

    try {
        factory = ctor.newInstance(ctorArg);
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();

        throw (t instanceof Exception) ? ((Exception) t)
                                       : new RuntimeException(
                                           t.toString());
    }

    return (HsqlSocketFactory) factory;
}
项目:Cybernet-VPN    文件:VpnProfile.java   
private String processSignJellyBeans(PrivateKey privkey, byte[] data) {
    try {
        Method getKey = privkey.getClass().getSuperclass().getDeclaredMethod("getOpenSSLKey");
        getKey.setAccessible(true);
        // Real object type is OpenSSLKey
        Object opensslkey = getKey.invoke(privkey);
        getKey.setAccessible(false);
        Method getPkeyContext = opensslkey.getClass().getDeclaredMethod("getPkeyContext");
        // integer pointer to EVP_pkey
        getPkeyContext.setAccessible(true);
        int pkey = (Integer) getPkeyContext.invoke(opensslkey);
        getPkeyContext.setAccessible(false);
        // 112 with TLS 1.2 (172 back with 4.3), 36 with TLS 1.0
        byte[] signed_bytes = NativeUtils.rsasign(data, pkey);
        return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
    } catch (NoSuchMethodException | InvalidKeyException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
        VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
        return null;
    }
}
项目:msa-cucumber-appium    文件:Locator.java   
@Override
    public By getByLocator() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        By byLocator = null;
//        Class<By> cls = (Class<By>) Class.forName("org.openqa.selenium.By");
//        Method m = cls.getMethod(this.typeOfLocator, String[].class);
//        String[] params = {this.attributeValue};

        if(this.typeOfLocator.equals("id")){
            byLocator =  By.id(this.attributeValue);
        }else if(this.typeOfLocator.equals("css")){
            byLocator =  By.cssSelector(this.attributeValue);
        }

//        return (By) m.invoke(null, (Object) params);
        return byLocator;
    }
项目:java-driver    文件:GoGen.java   
private static List<String> structuralPropertyNamesOf(final List<Class<? extends ASTNode>> nodes) {
    final List<String> names = new ArrayList<>();
    for (final Class<? extends ASTNode> node : nodes) {
        try {
            final Method m = node.getDeclaredMethod("propertyDescriptors", int.class);
            final List l = (List) m.invoke(null, AST.JLS8);
            for (final Object o : l) {
                final StructuralPropertyDescriptor d = (StructuralPropertyDescriptor) o;
                names.add(d.getId());
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
            throw new RuntimeException("unexpected exception", ex);
        }
    }
    return names;
}
项目:n4js    文件:StringLiteralForSTEImpl.java   
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
    switch (operationID) {
        case ImPackage.STRING_LITERAL_FOR_STE___GET_VALUE_AS_STRING:
            return getValueAsString();
    }
    return super.eInvoke(operationID, arguments);
}
项目:TitanCompanion    文件:AdventureFragment.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
private void incDec(final Adventure adv, final Class clazz, final String getMethod, final String setMethod, final Integer maxValue, final Object this_, boolean increase)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Method mGetMethod;
    Method mSetMethod;
    Object instance;

    if (adv != null) {
        mGetMethod = clazz.getMethod(getMethod);
        mSetMethod = clazz.getMethod(setMethod, int.class);
        instance = adv;
    } else {
        mGetMethod = this_.getClass().getMethod(getMethod);
        mSetMethod = this_.getClass().getMethod(setMethod, int.class);
        instance = this_;
    }

    if (increase)
        mSetMethod.invoke(instance, Math.min(((Integer) mGetMethod.invoke(instance)) + 1, maxValue));
    else
        mSetMethod.invoke(instance, Math.max(((Integer) mGetMethod.invoke(instance)) - 1, 0));
}
项目:localcloud_fe    文件:PermissionHelper.java   
/**
 * Requests "dangerous" permissions for the application at runtime. This is a helper method
 * alternative to cordovaInterface.requestPermissions() that does not require the project to be
 * built with cordova-android 5.0.0+
 *
 * @param plugin        The plugin the permissions are being requested for
 * @param requestCode   A requestCode to be passed to the plugin's onRequestPermissionResult()
 *                      along with the result of the permissions request
 * @param permissions   The permissions to be requested
 */
public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {
    try {
        Method requestPermission = CordovaInterface.class.getDeclaredMethod(
                "requestPermissions", CordovaPlugin.class, int.class, String[].class);

        // If there is no exception, then this is cordova-android 5.0.0+
        requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions);
    } catch (NoSuchMethodException noSuchMethodException) {
        // cordova-android version is less than 5.0.0, so permission is implicitly granted
        LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions));

        // Notify the plugin that all were granted by using more reflection
        deliverPermissionResult(plugin, requestCode, permissions);
    } catch (IllegalAccessException illegalAccessException) {
        // Should never be caught; this is a public method
        LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException);
    } catch(InvocationTargetException invocationTargetException) {
        // This method does not throw any exceptions, so this should never be caught
        LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException);
    }
}
项目:centraldogma    文件:DefaultCentralDogma.java   
private static <T> CompletableFuture<T> run(ThriftCall<T> call) {
    ThriftCompletableFuture<T> future = new ThriftCompletableFuture<>();
    try {
        call.apply(future);
    } catch (Exception e) {
        final Throwable cause;
        if (e instanceof InvocationTargetException) {
            cause = MoreObjects.firstNonNull(e.getCause(), e);
        } else {
            cause = e;
        }
        CompletableFuture<T> failedFuture = new CompletableFuture<>();
        failedFuture.completeExceptionally(cause);
        return failedFuture;
    }
    return future;
}
项目:Jupiter    文件:BaseChunk.java   
@Override
public boolean setBlock(int x, int y, int z, Integer blockId, Integer meta) {
    int id = blockId == null ? 0 : blockId;
    int damage = meta == null ? 0 : meta;
    try {
        this.hasChanged = true;
        return this.sections[y >> 4].setBlock(x, y & 0x0f, z, id, damage);
    } catch (ChunkException e) {
        int Y = y >> 4;
        try {
            this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
            Server.getInstance().getLogger().logException(e1);
        }
        return this.sections[y >> 4].setBlock(x, y & 0x0f, z, id, damage);
    }
}
项目:Hydrograph    文件:ExpressionEditorUtil.java   
/**
 * This method validates the given expression and updates the expression-editor's datasturcture accordingly
 * 
 * @param expressionText
 * @param inputFields
 * @param expressionEditorData
 */
public static void validateExpression(String expressionText,Map<String, Class<?>> inputFields,ExpressionEditorData expressionEditorData ) {
    if(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()!=null){
    DiagnosticCollector<JavaFileObject> diagnosticCollector = null;
    try {
        inputFields.putAll(expressionEditorData.getExtraFieldDatatypeMap());
        diagnosticCollector = ValidateExpressionToolButton
                .compileExpresion(expressionText,inputFields,expressionEditorData.getComponentName());
        if (diagnosticCollector != null && !diagnosticCollector.getDiagnostics().isEmpty()) {
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
                    expressionEditorData.setValid(false);
                    return;
                }
            }
        }
    } catch (JavaModelException | InvocationTargetException | ClassNotFoundException | MalformedURLException
            | IllegalAccessException | IllegalArgumentException e) {
        expressionEditorData.setValid(false);
        return;
    }
    expressionEditorData.setValid(true);
    }
}
项目:cyberduck    文件:VaultFactory.java   
private Vault create(final Path directory, final PasswordStore keychain) {
    final String clazz = PreferencesFactory.get().getProperty("factory.vault.class");
    if(null == clazz) {
        throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
    }
    try {
        final Class<Vault> name = (Class<Vault>) Class.forName(clazz);
        final Constructor<Vault> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
                directory.getClass(), keychain.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", directory.getClass()));
            // Call default constructor for disabled implementations
            return name.newInstance();
        }
        return constructor.newInstance(directory, keychain);
    }
    catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return Vault.DISABLED;
    }
}
项目:JavaTutorial    文件:AMethodProcess.java   
public static void initMethod(Object object) throws InvocationTargetException, IllegalAccessException {
    if (object instanceof User) {
        Class clz = object.getClass();
        Method [] methods = clz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(AMethod.class)) {
                if(Modifier.isPrivate(method.getModifiers())){
                    method.setAccessible(true);
                }else {
                    AMethod aMethod =  method.getAnnotation(AMethod.class);
                    System.out.println(aMethod.method() + "时间为 " + aMethod.value());
                    method.invoke(object);
                }
            }
        }
    }else {
        throw new RuntimeException("无法向下转型成指定类");
    }
}
项目:VoxelScript    文件:Script.java   
public void unload(CommandSource sender) {
    if (this.status != Status.LOADED && this.status != Status.UPDATED) {
        return;
    }

    Method onUnload = this.compiled.getMethod(this.id, "onUnload", "()V");
    if (onUnload != null) {
        try {
            onUnload.invoke(null, (Object[]) null);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            VoxelScript.getLogger().error("Error calling " + this.id + "#onUnload()V");
            e.printStackTrace();
        }
    }
    this.src = null;
    this.compiled = null;
    this.status = Status.UNLOADED;
    sender.sendMessage(Text.of(TextColors.GREEN, "Script " + this.id + " unloaded"));
}
项目:apache-tomcat-7.0.73-with-comment    文件:StatementCache.java   
@Override
protected Object createDecorator(Object proxy, Method method, Object[] args,
                                 Object statement, Constructor<?> constructor, String sql)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
    boolean process = process(this.types, method, false);
    if (process) {
        Object result = null;
        CachedStatement statementProxy = new CachedStatement((Statement)statement,sql);
        result = constructor.newInstance(new Object[] { statementProxy });
        statementProxy.setActualProxy(result);
        statementProxy.setConnection(proxy);
        statementProxy.setConstructor(constructor);
        statementProxy.setCacheKey(createCacheKey(method, args));
        return result;
    } else {
        return super.createDecorator(proxy, method, args, statement, constructor, sql);
    }
}
项目:fastdfs-spring-boot    文件:FastdfsHandler.java   
private Throwable translateException(Throwable cause) {
    if (cause instanceof FastdfsException) {
        return cause;
    }

    Throwable unwrap = cause;
    for (; ; ) {

        if (unwrap instanceof InvocationTargetException) {
            unwrap = ((InvocationTargetException) unwrap).getTargetException();
            continue;
        }

        if (unwrap instanceof UndeclaredThrowableException) {
            unwrap = ((UndeclaredThrowableException) unwrap).getUndeclaredThrowable();
            continue;
        }

        break;
    }

    return new FastdfsException("fastdfs operation error.", unwrap);
}
项目:alerta-fraude    文件:PermissionHelper.java   
/**
 * Requests "dangerous" permissions for the application at runtime. This is a helper method
 * alternative to cordovaInterface.requestPermissions() that does not require the project to be
 * built with cordova-android 5.0.0+
 *
 * @param plugin        The plugin the permissions are being requested for
 * @param requestCode   A requestCode to be passed to the plugin's onRequestPermissionResult()
 *                      along with the result of the permissions request
 * @param permissions   The permissions to be requested
 */
public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {
    try {
        Method requestPermission = CordovaInterface.class.getDeclaredMethod(
                "requestPermissions", CordovaPlugin.class, int.class, String[].class);

        // If there is no exception, then this is cordova-android 5.0.0+
        requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions);
    } catch (NoSuchMethodException noSuchMethodException) {
        // cordova-android version is less than 5.0.0, so permission is implicitly granted
        LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions));

        // Notify the plugin that all were granted by using more reflection
        deliverPermissionResult(plugin, requestCode, permissions);
    } catch (IllegalAccessException illegalAccessException) {
        // Should never be caught; this is a public method
        LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException);
    } catch(InvocationTargetException invocationTargetException) {
        // This method does not throw any exceptions, so this should never be caught
        LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException);
    }
}
项目:openjdk-jdk10    文件:TrySetAccessibleTest.java   
/**
 * Invoke a private method on a public class in an open package
 */
public void testPrivateMethodInOpenedPackage() throws Exception {
    Method m = Unsafe.class.getDeclaredMethod("throwIllegalAccessError");
    assertFalse(m.canAccess(null));

    try {
        m.invoke(null);
        assertTrue(false);
    } catch (IllegalAccessException expected) { }

    assertTrue(m.trySetAccessible());
    assertTrue(m.canAccess(null));
    try {
        m.invoke(null);
        assertTrue(false);
    } catch (InvocationTargetException e) {
        // thrown by throwIllegalAccessError
        assertTrue(e.getCause() instanceof IllegalAccessError);
    }
}
项目:incubator-netbeans    文件:DebuggingJSTreeExpansionModelFilter.java   
private void currentStackFrameChanged(CallStackFrame csf) {
    if (csf != null && csf.getClassName().startsWith(JSUtils.NASHORN_SCRIPT)) {
        JPDAThread thread = csf.getThread();
        suspendedNashornThread = new WeakReference<>(thread);
        try {
            Object node = dvSupport.getClass().getMethod("get", JPDAThread.class).invoke(dvSupport, thread);
            boolean explicitCollaps;
            synchronized (this) {
                explicitCollaps = collapsedExplicitly.contains(node);
            }
            if (!explicitCollaps) {
                fireNodeExpanded(node);
            }
        } catch (IllegalAccessException | IllegalArgumentException |
                 InvocationTargetException | NoSuchMethodException |
                 SecurityException ex) {
            Exceptions.printStackTrace(ex);
        }
    } else {
        suspendedNashornThread = NO_THREAD;
    }
}
项目:ProyectoPacientes    文件:WrapperBase.java   
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if ("equals".equals(method.getName())) {
        // Let args[0] "unwrap" to its InvocationHandler if it is a proxy.
        return args[0].equals(this);
    }

    Object result = null;

    try {
        result = method.invoke(this.invokeOn, args);

        if (result != null) {
            result = proxyIfInterfaceIsJdbc(result, result.getClass());
        }
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof SQLException) {
            checkAndFireConnectionError((SQLException) e.getTargetException());
        } else {
            throw e;
        }
    }

    return result;
}
项目:doctemplate    文件:PropertyUtils.java   
public static Object getNestedProperty(Object bean, String nestedProperty)
        throws IllegalArgumentException, SecurityException, IllegalAccessException,
        InvocationTargetException, IntrospectionException, NoSuchMethodException {
    Object object = null;
    StringTokenizer st = new StringTokenizer(nestedProperty, ".", false);
    while (st.hasMoreElements() && bean != null) {
        String nam = (String) st.nextElement();
        if (st.hasMoreElements()) {
            bean = getProperty(bean, nam);
        }
        else {
            object = getProperty(bean, nam);
        }
    }
    return object;
}
项目:container    文件:ProxyServiceFactory.java   
@Override
public IBinder getService(final Context context, ClassLoader classLoader, IBinder binder) {
    return new StubBinder(classLoader, binder) {
        @Override
        public InvocationHandler createHandler(Class<?> interfaceClass, final IInterface base) {
            return new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(base, args);
                    } catch (InvocationTargetException e) {
                        if (e.getCause() != null) {
                            throw e.getCause();
                        }
                        throw e;
                    }
                }
            };
        }
    };
}
项目:Graphene    文件:RelationExtractionRunner.java   
public RelationExtractionRunner(Config config) {

        // load boolean values
        this.exploitCore = config.getBoolean("exploit-core");
        this.exploitContexts = config.getBoolean("exploit-contexts");
        this.separateNounBased = config.getBoolean("separate-noun-based");
        this.separatePurposes = config.getBoolean("separate-purposes");
        this.separateAttributions = config.getBoolean("separate-attributions");

        // instantiate extractor
        String extractorClassName = config.getString("relation-extractor");
        try {
            Class<?> extractorClass = Class.forName(extractorClassName);
            Constructor<?> extractorConst = extractorClass.getConstructor();
            this.extractor = (RelationExtractor) extractorConst.newInstance();
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) {
            logger.error("Failed to create instance of {}", extractorClassName);
            throw new ConfigException.BadValue("relation-extractor." + extractorClassName, "Failed to create instance.");
        }

        this.elementCoreExtractionMap = new LinkedHashMap<>();
    }
项目:OpenJSharp    文件:Robot.java   
/**
 * Waits until all events currently on the event queue have been processed.
 * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 */
public synchronized void waitForIdle() {
    checkNotDispatchThread();
    // post a dummy event to the queue so we know when
    // all the events before it have been processed
    try {
        SunToolkit.flushPendingEvents();
        EventQueue.invokeAndWait( new Runnable() {
                                        public void run() {
                                            // dummy implementation
                                        }
                                    } );
    } catch(InterruptedException ite) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ite.printStackTrace();
    } catch(InvocationTargetException ine) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ine.printStackTrace();
    }
}
项目:rapidminer    文件:AbstractLogicalCondition.java   
public AbstractLogicalCondition(Element element) throws XMLException {
    super(element);
    // get all condition xml-elements
    Element conditionsElement = XMLTools.getChildElement(element, getXMLTag(), true);
    Collection<Element> conditionElements = XMLTools.getChildElements(conditionsElement, ELEMENT_CONDITION);
    conditions = new ParameterCondition[conditionElements.size()];

    // iterate over condition xml-elements
    int idx = 0;
    for (Element conditionElement : conditionElements) {
        // try to construct a condition object
        String className = conditionElement.getAttribute(ATTRIBUTE_CONDITION_CLASS);
        Class<?> conditionClass;
        try {
            conditionClass = Class.forName(className);
            Constructor<?> constructor = conditionClass.getConstructor(Element.class);
            conditions[idx] = (ParameterCondition) constructor.newInstance(conditionElement);
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new XMLException("Illegal value for attribute " + ATTRIBUTE_CONDITION_CLASS, e);
        }
        ++idx;
    }
}
项目:zooadmin    文件:BeanMapUtil.java   
public static Object convertMap2Bean(Class type, Map map)
        throws IntrospectionException, IllegalAccessException,
        InstantiationException, InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(type);
    Object obj = type.newInstance();
    PropertyDescriptor[] propertyDescriptors = beanInfo
            .getPropertyDescriptors();
    for (PropertyDescriptor pro : propertyDescriptors) {
        String propertyName = pro.getName();
        if (pro.getPropertyType().getName().equals("java.lang.Class")) {
            continue;
        }
        if (map.containsKey(propertyName)) {
            Object value = map.get(propertyName);
            Method setter = pro.getWriteMethod();
            setter.invoke(obj, value);
        }
    }
    return obj;
}
项目:WC    文件:WCUser.java   
public void sendHeaderAndFooter(String headerText, String footerText) {
    try {
        Class chatSerializer = ReflectionAPI.getNmsClass("IChatBaseComponent$ChatSerializer");

        Object tabHeader = chatSerializer.getMethod("a", String.class).invoke(chatSerializer, "{'text': '" + Utils.colorize(headerText) + "'}");
        Object tabFooter = chatSerializer.getMethod("a", String.class).invoke(chatSerializer, "{'text': '" + Utils.colorize(footerText) + "'}");
        Object tab = ReflectionAPI.getNmsClass("PacketPlayOutPlayerListHeaderFooter").getConstructor(new Class[]{ReflectionAPI.getNmsClass("IChatBaseComponent")}).newInstance(new Object[]{tabHeader});

        Field f = tab.getClass().getDeclaredField("b");
        f.setAccessible(true);
        f.set(tab, tabFooter);

        ReflectionAPI.sendPacket(getPlayer(), tab);
    } catch (IllegalAccessException | InstantiationException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | NoSuchFieldException e) {
        e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:MetaData.java   
/**
 * Invoke Timstamp getNanos.
 */
private static int getNanos(Object obj) {
    if (getNanosMethod == null)
        throw new AssertionError("Should not get here");
    try {
        return (Integer)getNanosMethod.invoke(obj);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof RuntimeException)
            throw (RuntimeException)cause;
        if (cause instanceof Error)
            throw (Error)cause;
        throw new AssertionError(e);
    } catch (IllegalAccessException iae) {
        throw new AssertionError(iae);
    }
}
项目:the-vigilantes    文件:StringUtils.java   
/**
 * Takes care of the fact that Sun changed the output of
 * BigDecimal.toString() between JDK-1.4 and JDK 5
 * 
 * @param decimal
 *            the big decimal to stringify
 * 
 * @return a string representation of 'decimal'
 */
public static String consistentToString(BigDecimal decimal) {
    if (decimal == null) {
        return null;
    }

    if (toPlainStringMethod != null) {
        try {
            return (String) toPlainStringMethod.invoke(decimal, (Object[]) null);
        } catch (InvocationTargetException invokeEx) {
            // that's okay, we fall-through to decimal.toString()
        } catch (IllegalAccessException accessEx) {
            // that's okay, we fall-through to decimal.toString()
        }
    }

    return decimal.toString();
}
项目:springboot-spwa-gae-demo    文件:MethodAccessor.java   
@SuppressWarnings("unchecked")
@Override
public V get(T t) {
    try {
        return (V) method.invoke(t);
    } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
        throw new SearchException(e, "Failed to call method '%s.%s': %s", type.getSimpleName(), methodName, e.getMessage());
    }
}
项目:FlickLauncher    文件:ShortcutPackageParser.java   
@SuppressLint("PrivateApi")
private int loadApkIntoAssetManager() throws PackageManager.NameNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(mPackageName,
            PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES);

    Method addAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
    int cookie = (int) addAssetPath.invoke(mAssets, info.publicSourceDir);
    if (cookie == 0) {
        throw new RuntimeException("Failed adding asset path: " + info.publicSourceDir);
    }
    return cookie;
}
项目:AstralEdit    文件:ReflectionUtils.java   
/**
 * Invokes the static method of the given clazz, name, paramTypes, params
 *
 * @param clazz      clazz
 * @param name       name
 * @param paramTypes paramTypes
 * @param params     params
 * @param <T>        returnType
 * @return returnValue
 * @throws NoSuchMethodException     exception
 * @throws InvocationTargetException exception
 * @throws IllegalAccessException    exception
 */
public static <T> T invokeMethodByClass(Class<?> clazz, String name, Class<?>[] paramTypes, Object[] params) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (clazz == null)
        throw new IllegalArgumentException("Class cannot be null!");
    if (name == null)
        throw new IllegalArgumentException("Name cannot be null!");
    if (paramTypes == null)
        throw new IllegalArgumentException("ParamTypes cannot be null");
    if (params == null)
        throw new IllegalArgumentException("Params cannot be null!");
    final Method method = clazz.getDeclaredMethod(name, paramTypes);
    method.setAccessible(true);
    return (T) method.invoke(null, params);
}
项目:GitHub    文件:EnumIT.java   
@Test
@SuppressWarnings({ "unchecked" })
public void enumWithCustomJavaNames() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithCustomJavaNames.json", "com.example");

    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames$EnumProperty");

    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setEnumProperty", enumClass);
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]);
    assertThat(enumClass.getEnumConstants()[0].name(), is("ONE"));
    assertThat(enumClass.getEnumConstants()[1].name(), is("TWO"));
    assertThat(enumClass.getEnumConstants()[2].name(), is("THREE"));
    assertThat(enumClass.getEnumConstants()[3].name(), is("FOUR"));

    ObjectMapper objectMapper = new ObjectMapper();

    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));
    assertThat(jsonTree.has("enum_Property"), is(true));
    assertThat(jsonTree.get("enum_Property").isTextual(), is(true));
    assertThat(jsonTree.get("enum_Property").asText(), is("3"));
}
项目:codelens-eclipse    文件:StyledTextPatcher.java   
private static void initialize(Object styledTextRenderer, StyledText styledText)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    // renderer.setContent(content);
    Method m1 = getSetContentMethod(styledTextRenderer);
    m1.invoke(styledTextRenderer, styledText.getContent());
    // renderer.setFont(getFont(), tabLength);
    Method m2 = getSetFontMethod(styledTextRenderer);
    m2.invoke(styledTextRenderer, styledText.getFont(), 4);
}
项目:monarch    文件:GfshParser.java   
private Map<Short, List<CommandTarget>> findMatchingCommands(String userSpecifiedCommand,
    Set<String> requiredCommands)
    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

  Map<String, CommandTarget> existingCommands = getRequiredCommandTargets(requiredCommands);
  CommandTarget exactCommandTarget = existingCommands.get(userSpecifiedCommand);

  // 1. First find exactly matching commands.
  List<CommandTarget> exactCommandTargets = Collections.emptyList();
  if (exactCommandTarget != null) {
    // This means that the user has entered the command
    // NOTE: we are not skipping synonym here.
    exactCommandTargets = Collections.singletonList(exactCommandTarget);
  }

  // 2. Now find command names that start with 'userSpecifiedCommand'
  List<CommandTarget> possibleCommandTargets = new ArrayList<CommandTarget>();
  // Now we need to locate the CommandTargets from the entries in the map
  for (Map.Entry<String, CommandTarget> entry : existingCommands.entrySet()) {
    CommandTarget commandTarget = entry.getValue();
    String commandName = commandTarget.getCommandName();
    // This check is done to remove commands that are synonyms as
    // CommandTarget.getCommandName() will return name & not a synonym
    if (entry.getKey().equals(commandName)) {
      if (commandName.startsWith(userSpecifiedCommand)
          && !commandTarget.equals(exactCommandTarget)) {
        // This means that the user is yet to enter the command properly
        possibleCommandTargets.add(commandTarget);
      }
    }
  }

  Map<Short, List<CommandTarget>> commandTargetsArr = new HashMap<Short, List<CommandTarget>>();
  commandTargetsArr.put(EXACT_TARGET, exactCommandTargets);
  commandTargetsArr.put(MATCHING_TARGETS, possibleCommandTargets);
  return commandTargetsArr;
}
项目:jdk8u-jdk    文件:CViewEmbeddedFrame.java   
@SuppressWarnings("deprecation")
public void validateWithBounds(final int x, final int y, final int width, final int height) {
    try {
        LWCToolkit.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                ((LWWindowPeer) getPeer()).setBoundsPrivate(0, 0, width, height);
                validate();
                setVisible(true);
            }
        }, this);
    } catch (InvocationTargetException ex) {}
}
项目:Open_Source_ECOA_Toolset_AS5    文件:ReqResServicePage.java   
@Override
protected void setValue(Object element, Object value) {
    Parameter val = (Parameter) element;
    try {
        Method setter = val.getClass().getMethod(StringUtils.replaceFirst(fName, "get", "set"), String.class);
        setter.invoke(element, value);
    } catch (IllegalArgumentException | IllegalAccessException | SecurityException | NoSuchMethodException | InvocationTargetException e) {
    }
    viewer.update(element, null);
}