Java Code Examples for java.lang.reflect.InvocationTargetException

The following are top voted examples for showing how to use java.lang.reflect.InvocationTargetException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: DebuggingJSTreeExpansionModelFilter.java   Source Code and License 8 votes vote down vote up
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;
    }
}
 
Example 2
Project: Netherboard   File: BPlayerBoard.java   Source Code and License 8 votes vote down vote up
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);
    }
}
 
Example 3
Project: parabuild-ci   File: HsqlSocketFactory.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 4
Project: Cybernet-VPN   File: VpnProfile.java   Source Code and License 7 votes vote down vote up
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;
    }
}
 
Example 5
Project: alfresco-repository   File: ACLEntryVoterTest.java   Source Code and License 7 votes vote down vote up
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)
    {

    }
}
 
Example 6
Project: ares   File: ReflectionManager.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 7
Project: fastdfs-spring-boot   File: FastdfsHandler.java   Source Code and License 7 votes vote down vote up
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);
}
 
Example 8
Project: openjdk-jdk10   File: TrySetAccessibleTest.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
Project: Java-EX   File: AnnotationUtil.java   Source Code and License 6 votes vote down vote up
/**
 * @param c
 * @param annotation
 * @author [email protected]
 * @see <a href="https://stackoverflow.com/a/30287201/7803527">Origin code on stackoverflow</a>
 * @see java.lang.Class
 * @see #createAnnotationFromMap(Class, Map)
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> void addAnnotation(Class<?> c, T annotation) {
  try {
    while (true) { // retry loop
      int classRedefinedCount = Class_classRedefinedCount.getInt(c);
      Object /* AnnotationData */ annotationData = Class_annotationData.invoke(c);
      // null or stale annotationData -> optimistically create new instance
      Object newAnnotationData = changeClassAnnotationData(c, annotationData, (Class<T>) annotation.annotationType(),
          annotation, classRedefinedCount, true).getLeft();
      // try to install it
      if ((boolean) Atomic_casAnnotationData.invoke(Atomic_class, c, annotationData, newAnnotationData)) {
        // successfully installed new AnnotationData
        break;
      }
    }
  } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 10
Project: msa-cucumber-appium   File: Locator.java   Source Code and License 6 votes vote down vote up
@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;
    }
 
Example 11
Project: java-driver   File: GoGen.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 12
Project: n4js   File: StringLiteralForSTEImpl.java   Source Code and License 6 votes vote down vote up
/**
 * <!-- 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);
}
 
Example 13
Project: TitanCompanion   File: AdventureFragment.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 14
Project: localcloud_fe   File: PermissionHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 15
Project: centraldogma   File: DefaultCentralDogma.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 16
Project: Jupiter   File: BaseChunk.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 17
Project: Hydrograph   File: ExpressionEditorUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 18
Project: cyberduck   File: VaultFactory.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 19
Project: JavaTutorial   File: AMethodProcess.java   Source Code and License 6 votes vote down vote up
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("无法向下转型成指定类");
    }
}
 
Example 20
Project: VoxelScript   File: Script.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 21
Project: apache-tomcat-7.0.73-with-comment   File: StatementCache.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 22
Project: alerta-fraude   File: PermissionHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 23
Project: ProyectoPacientes   File: WrapperBase.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 24
Project: doctemplate   File: PropertyUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 25
Project: container   File: ProxyServiceFactory.java   Source Code and License 6 votes vote down vote up
@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;
					}
				}
			};
		}
	};
}
 
Example 26
Project: Graphene   File: RelationExtractionRunner.java   Source Code and License 6 votes vote down vote up
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<>();
	}
 
Example 27
Project: OpenJSharp   File: Robot.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 28
Project: rapidminer   File: AbstractLogicalCondition.java   Source Code and License 6 votes vote down vote up
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;
	}
}
 
Example 29
Project: zooadmin   File: BeanMapUtil.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 30
Project: WC   File: WCUser.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 31
Project: openjdk-jdk10   File: MetaData.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 32
Project: the-vigilantes   File: StringUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 33
Project: springboot-spwa-gae-demo   File: MethodAccessor.java   Source Code and License 5 votes vote down vote up
@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());
    }
}
 
Example 34
Project: FlickLauncher   File: ShortcutPackageParser.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 35
Project: AstralEdit   File: ReflectionUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 36
Project: GitHub   File: EnumIT.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 37
Project: codelens-eclipse   File: StyledTextPatcher.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 38
Project: monarch   File: GfshParser.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: jdk8u-jdk   File: CViewEmbeddedFrame.java   Source Code and License 5 votes vote down vote up
@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) {}
}
 
Example 40
Project: Open_Source_ECOA_Toolset_AS5   File: ReqResServicePage.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 41
Project: TOSCA-Studio   File: Tosca_nodes_databaseImpl.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
@SuppressWarnings("unchecked")
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
	switch (operationID) {
		case ToscaPackage.TOSCA_NODES_DATABASE___APPLIES_CONSTRAINT__DIAGNOSTICCHAIN_MAP:
			return appliesConstraint((DiagnosticChain)arguments.get(0), (Map<Object, Object>)arguments.get(1));
	}
	return super.eInvoke(operationID, arguments);
}
 
Example 42
Project: boohee_v5.6   File: Platform.java   Source Code and License 5 votes vote down vote up
public void untagSocket(Socket socket) throws SocketException {
    if (this.trafficStatsUntagSocket != null) {
        try {
            this.trafficStatsUntagSocket.invoke(null, new Object[]{socket});
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e2) {
            throw new RuntimeException(e2.getCause());
        }
    }
}
 
Example 43
Project: jaer   File: FilterPanel.java   Source Code and License 5 votes vote down vote up
@Override
            public void actionPerformed(ActionEvent e) {
//                    System.out.println(e);
                try {
                    Object arg = null;
                    writeMethod.invoke(filter, arg);
                    set(null);
                } catch (InvocationTargetException ite) {
                    ite.printStackTrace();
                } catch (IllegalAccessException iae) {
                    iae.printStackTrace();
                }
            }
 
Example 44
Project: enigma-vk   File: ClassRenamer.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void renameAttributes(List<AttributeInfo> attributes, ReplacerClassMap map, SignatureType type) {
	try {
		
		// make the rename class method accessible
		Method renameClassMethod = AttributeInfo.class.getDeclaredMethod("renameClass", Map.class);
		renameClassMethod.setAccessible(true);
		
		for (AttributeInfo attribute : attributes) {
			if (attribute instanceof SignatureAttribute) {
				// this has to be handled specially because SignatureAttribute.renameClass() is buggy as hell
				SignatureAttribute signatureAttribute = (SignatureAttribute)attribute;
				String newSignature = type.rename(signatureAttribute.getSignature(), map);
				if (newSignature != null) {
					signatureAttribute.setSignature(newSignature);
				}
			} else if (attribute instanceof CodeAttribute) {
				// code attributes have signature attributes too (indirectly)
				CodeAttribute codeAttribute = (CodeAttribute)attribute;
				renameAttributes(codeAttribute.getAttributes(), map, type);
			} else if (attribute instanceof LocalVariableTypeAttribute) {
				// lvt attributes have signature attributes too
				LocalVariableTypeAttribute localVariableAttribute = (LocalVariableTypeAttribute)attribute;
				renameLocalVariableTypeAttribute(localVariableAttribute, map);
			} else {
				renameClassMethod.invoke(attribute, map);
			}
		}
		
	} catch(NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
		throw new Error("Unable to call javassist methods by reflection!", ex);
	}
}
 
Example 45
Project: SDgen   File: ReflectionUtils.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public static <T> T buildWithConstructor(Class<T> toBuild, Object... args) {
    for (Constructor<?> constructor : toBuild.getDeclaredConstructors()) {
        if (constructor.getParameterCount() == args.length) {
            try {
                return (T) constructor.newInstance(args);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new IllegalArgumentException("Couldn't construct a new object of type: " + toBuild + " using it's 0 args constructor!", e);
            }
        }
    }
    throw new IllegalArgumentException("No " + args.length + " args constructor found in class: " + toBuild);
}
 
Example 46
Project: ares   File: SystemAnalyzer.java   Source Code and License 5 votes vote down vote up
/**
 * Produces a {@link Report}.
 * @return the report produced.
 * @throws BotAnalysisException when analysis cannot be correctly executed.
 */
@Override
public Report makeReport() throws BotAnalysisException {
  SystemFeatures features = SystemFeatures.getLocal();
  Map<String,Object> attributes;
  try {
    attributes = ReflectionManager.getAttributes(SystemFeatures.class, features);
  } catch (IntrospectionException | InvocationTargetException | IllegalAccessException exc) {
    attributes = new HashMap<>();
  }
  return new SimpleReport(attributes);
}
 
Example 47
Project: GitHub   File: DelegatingSSLSocket.java   Source Code and License 5 votes vote down vote up
public String getHandshakeApplicationProtocol() {
  try {
    return (String) SSLSocket.class.getMethod("getHandshakeApplicationProtocol").invoke(delegate);
  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new AssertionError();
  }
}
 
Example 48
Project: incubator-netbeans   File: PinWatchValueProvider.java   Source Code and License 5 votes vote down vote up
@NbBundle.Messages({"# {0} - the watched expression", "PropEditDisplayName=Value of {0}"})
private Action getPropertyEditorAction(final PropertyEditor pe,
                                       final ObjectVariable var,
                                       final ValueListeners vl,
                                       final String expression) {
    Property property = new PropertySupport.ReadWrite(expression, null,
                                                      Bundle.PropEditDisplayName(expression),
                                                      Bundle.PropEditDisplayName(expression)) {
        @Override
        public Object getValue() throws IllegalAccessException, InvocationTargetException {
            return var;
        }
        @Override
        public void setValue(final Object val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            RP.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        vl.watchEv.setFromMirrorObject(val);
                        vl.watchEv.setEvaluated(null);
                        updateValueFrom(vl.watchEv);
                    } catch (InvalidObjectException ex) {
                        NotifyDescriptor msg = new NotifyDescriptor.Message(ex.getLocalizedMessage(), NotifyDescriptor.ERROR_MESSAGE);
                        DialogDisplayer.getDefault().notifyLater(msg);
                    }
                }
            });
            vl.value = getEvaluatingText();
            vl.valueOnly = null;

        }
        @Override
        public PropertyEditor getPropertyEditor() {
            return pe;
        }
    };
    PropertyPanel pp = new PropertyPanel(property);
    return pp.getActionMap().get("invokeCustomEditor");                     // NOI18N
}
 
Example 49
Project: OpenJSharp   File: ExecutableInputMethodManager.java   Source Code and License 5 votes vote down vote up
private void showInputMethodMenuOnRequesterEDT(Component requester)
    throws InterruptedException, InvocationTargetException {

    if (requester == null){
        return;
    }

    class AWTInvocationLock {}
    Object lock = new AWTInvocationLock();

    InvocationEvent event =
            new InvocationEvent(requester,
                                new Runnable() {
                                    public void run() {
                                        showInputMethodMenu();
                                    }
                                },
                                lock,
                                true);

    AppContext requesterAppContext = SunToolkit.targetToAppContext(requester);
    synchronized (lock) {
        SunToolkit.postEvent(requesterAppContext, event);
        while (!event.isDispatched()) {
            lock.wait();
        }
    }

    Throwable eventThrowable = event.getThrowable();
    if (eventThrowable != null) {
        throw new InvocationTargetException(eventThrowable);
    }
}
 
Example 50
Project: hadoop   File: ProgramDriver.java   Source Code and License 5 votes vote down vote up
/**
 * Invoke the example application with the given arguments
 * @param args the arguments for the application
 * @throws Throwable The exception thrown by the invoked method
 */
public void invoke(String[] args)
  throws Throwable {
  try {
    main.invoke(null, new Object[]{args});
  } catch (InvocationTargetException except) {
    throw except.getCause();
  }
}
 
Example 51
Project: googles-monorepo-demo   File: ClassSanityTester.java   Source Code and License 5 votes vote down vote up
void doTestNulls(Class<?> cls, Visibility visibility)
    throws ParameterNotInstantiableException, IllegalAccessException,
           InvocationTargetException, FactoryMethodReturnsNullException {
  if (!Modifier.isAbstract(cls.getModifiers())) {
    nullPointerTester.testConstructors(cls, visibility);
  }
  nullPointerTester.testStaticMethods(cls, visibility);
  if (hasInstanceMethodToTestNulls(cls, visibility)) {
    Object instance = instantiate(cls);
    if (instance != null) {
      nullPointerTester.testInstanceMethods(instance, visibility);
    }
  }
}
 
Example 52
Project: simple-keyboard   File: CompatUtils.java   Source Code and License 5 votes vote down vote up
public static Object newInstance(final Constructor<?> constructor, final Object ... args) {
    if (constructor == null) {
        return null;
    }
    try {
        return constructor.newInstance(args);
    } catch (final InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        Log.e(TAG, "Exception in newInstance", e);
    }
    return null;
}
 
Example 53
Project: apache-tomcat-7.0.73-with-comment   File: DefaultInstanceManager.java   Source Code and License 5 votes vote down vote up
/**
 * Inject resources in specified method.
 *
 * @param context  jndi context to extract value from
 * @param instance object to inject into
 * @param method   field target for injection
 * @param name     jndi name value is bound under
 * @param clazz    class annotation is defined in
 * @throws IllegalAccessException       if method is inaccessible
 * @throws javax.naming.NamingException if value is not accessible in naming context
 * @throws java.lang.reflect.InvocationTargetException
 *                                      if setter call fails
 */
protected static void lookupMethodResource(Context context,
        Object instance, Method method, String name, Class<?> clazz)
        throws NamingException, IllegalAccessException, InvocationTargetException {

    if (!Introspection.isValidSetter(method)) {
        throw new IllegalArgumentException(
                sm.getString("defaultInstanceManager.invalidInjection"));
    }

    Object lookedupResource;
    boolean accessibility;

    String normalizedName = normalize(name);

    if ((normalizedName != null) && (normalizedName.length() > 0)) {
        lookedupResource = context.lookup(normalizedName);
    } else {
        lookedupResource = context.lookup(
                clazz.getName() + "/" + Introspection.getPropertyName(method));
    }

    synchronized (method) {
        accessibility = method.isAccessible();
        method.setAccessible(true);
        method.invoke(instance, lookedupResource);
        method.setAccessible(accessibility);
    }
}
 
Example 54
Project: openjdk-jdk10   File: bug4213634.java   Source Code and License 5 votes vote down vote up
bug4213634() throws AWTException, InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
        }
    });

    test();
}
 
Example 55
Project: myfaces-trinidad   File: JavaMethod.java   Source Code and License 5 votes vote down vote up
@Override
public Object invoke(Object instance, Object[] args)
  throws IllegalAccessException, IllegalArgumentException,
         InvocationTargetException
{
  return _met.invoke(instance, args);
}
 
Example 56
Project: JavaCommon   File: Reflection.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
		throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
		SecurityException, IllegalArgumentException, InvocationTargetException {
	// 通过类名来构造一个类的实例
	Class cls_str = Class.forName("java.lang.String");
	// 上面这句很眼熟,因为使用过 JDBC 访问数据库的人都用过 J
	Object str = cls_str.newInstance();
	// 相当于 String str = new String();

	// 通过方法名来调用一个方法
	String methodName = "length";
	Method m = cls_str.getMethod(methodName, null);
	System.out.println("length is " + m.invoke(str, null));
	// 相当于 System.out.println(str.length());
}
 
Example 57
Project: n4js   File: ArrayLikeImpl.java   Source Code and License 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
	switch (operationID) {
		case TypesPackage.ARRAY_LIKE___GET_ELEMENT_TYPE:
			return getElementType();
	}
	return super.eInvoke(operationID, arguments);
}
 
Example 58
Project: FontProvider   File: TypefaceCompatApi26.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Typeface createFromFamiliesWithDefault(Object families, int weight, int italic) {
    if (!available) {
        return null;
    }

    try {
        return (Typeface) createFromFamiliesWithDefaultMethod.invoke(null, families,
                weight, italic);
    } catch (IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 59
Project: lazycat   File: ApplicationContextFacade.java   Source Code and License 5 votes vote down vote up
/**
 * Executes the method of the specified <code>ApplicationContext</code>
 * 
 * @param method
 *            The method object to be invoked.
 * @param context
 *            The ApplicationContext 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);
	}
}
 
Example 60
Project: bootstrap   File: CsvJpaReader.java   Source Code and License 5 votes vote down vote up
/**
 * Initialize or update cache.
 */
private void ensureCache(final Field jpaField, final String propertyName)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	if (!foreignCache.containsKey(jpaField.getType()) || jpaField.getType() == clazz) {
		foreignCache.put(jpaField.getType(), buildMap(readAll(jpaField), propertyName));
	}
}