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: Netherboard File: BPlayerBoard.java View source code | 8 votes |
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 2
Project: parabuild-ci File: HsqlSocketFactory.java View source code | 7 votes |
/** * 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 3
Project: Cybernet-VPN File: VpnProfile.java View source code | 7 votes |
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 4
Project: alfresco-repository File: ACLEntryVoterTest.java View source code | 7 votes |
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 5
Project: ares File: ReflectionManager.java View source code | 7 votes |
/** * 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 6
Project: openjdk-jdk10 File: TrySetAccessibleTest.java View source code | 7 votes |
/** * 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 7
Project: incubator-netbeans File: DebuggingJSTreeExpansionModelFilter.java View source code | 7 votes |
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 8
Project: Java-EX File: AnnotationUtil.java View source code | 6 votes |
/** * @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 9
Project: msa-cucumber-appium File: Locator.java View source code | 6 votes |
@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 10
Project: java-driver File: GoGen.java View source code | 6 votes |
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 11
Project: n4js File: StringLiteralForSTEImpl.java View source code | 6 votes |
/** * <!-- 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 12
Project: TitanCompanion File: AdventureFragment.java View source code | 6 votes |
@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 13
Project: localcloud_fe File: PermissionHelper.java View source code | 6 votes |
/** * 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 14
Project: centraldogma File: DefaultCentralDogma.java View source code | 6 votes |
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 15
Project: Jupiter File: BaseChunk.java View source code | 6 votes |
@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 16
Project: Hydrograph File: ExpressionEditorUtil.java View source code | 6 votes |
/** * 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 17
Project: cyberduck File: VaultFactory.java View source code | 6 votes |
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 18
Project: JavaTutorial File: AMethodProcess.java View source code | 6 votes |
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 19
Project: VoxelScript File: Script.java View source code | 6 votes |
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 20
Project: apache-tomcat-7.0.73-with-comment File: StatementCache.java View source code | 6 votes |
@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 21
Project: fastdfs-spring-boot File: FastdfsHandler.java View source code | 6 votes |
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 22
Project: alerta-fraude File: PermissionHelper.java View source code | 6 votes |
/** * 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 View source code | 6 votes |
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 View source code | 6 votes |
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 View source code | 6 votes |
@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 View source code | 6 votes |
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 View source code | 6 votes |
/** * 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 View source code | 6 votes |
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 View source code | 6 votes |
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 View source code | 6 votes |
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 View source code | 6 votes |
/** * 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 View source code | 6 votes |
/** * 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 View source code | 5 votes |
@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 View source code | 5 votes |
@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 View source code | 5 votes |
/** * 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 View source code | 5 votes |
@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 View source code | 5 votes |
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 View source code | 5 votes |
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 View source code | 5 votes |
@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 View source code | 5 votes |
@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); }