List of usage examples for java.lang Class getMethod
@CallerSensitive public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:com.github.veithen.ulog.MetaFactory.java
private static LoggerFactoryBinder getLoggerFactoryBinder() { Class binderClass; try {/*from w ww .j a va 2 s . c o m*/ binderClass = MetaFactory.class.getClassLoader().loadClass("org.slf4j.impl.StaticLoggerBinder"); } catch (ClassNotFoundException ex) { return null; } try { return (LoggerFactoryBinder) binderClass.getMethod("getSingleton", new Class[0]).invoke(null, new Object[0]); } catch (InvocationTargetException ex) { logger.log(Level.WARNING, "Unable to get the SLF4J LoggerFactoryBinder", ex.getCause()); return null; } catch (Throwable ex) { logger.log(Level.WARNING, "Unable to get the SLF4J LoggerFactoryBinder", ex); return null; } }
From source file:com.hubrick.vertx.rest.converter.JacksonJsonHttpMessageConverter.java
private static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) { checkNotNull(clazz, "Class must not be null"); checkNotNull(methodName, "Method name must not be null"); if (paramTypes != null) { try {// w ww. j ava 2 s . co m return clazz.getMethod(methodName, paramTypes); } catch (NoSuchMethodException ex) { return null; } } else { Set<Method> candidates = new HashSet<>(1); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (methodName.equals(method.getName())) { candidates.add(method); } } if (candidates.size() == 1) { return candidates.iterator().next(); } return null; } }
From source file:com.izforge.izpack.integration.UninstallHelper.java
/** * Runs the destroyer obtained from the supplied container. * * @param container the container// w ww .j a va2 s .c o m * @param loader the isolated class loader to use to load classes * @throws Exception for any error */ private static void runDestroyer(Object container, ClassLoader loader, File jar) throws Exception { Method getComponent = container.getClass().getMethod("getComponent", Class.class); // get the destroyer class @SuppressWarnings("unchecked") Class<Destroyer> destroyerClass = (Class<Destroyer>) loader.loadClass(Destroyer.class.getName()); Object destroyer = getComponent.invoke(container, destroyerClass); Method forceDelete = destroyerClass.getMethod("setForceDelete", boolean.class); forceDelete.invoke(destroyer, true); // create the Destroyer and run it Method run = destroyerClass.getMethod("run"); run.invoke(destroyer); FileUtils.deleteQuietly(jar); // probably won't delete as the class loader will still have a reference to it? }
From source file:org.jfree.data.KeyToGroupMap.java
/** * Attempts to clone the specified object using reflection. * * @param object the object (<code>null</code> permitted). * * @return The cloned object, or the original object if cloning failed. *///from w w w .ja v a2 s. co m private static Object clone(Object object) { if (object == null) { return null; } Class c = object.getClass(); Object result = null; try { Method m = c.getMethod("clone", (Class[]) null); if (Modifier.isPublic(m.getModifiers())) { try { result = m.invoke(object, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } } catch (NoSuchMethodException e) { result = object; } return result; }
From source file:fr.jayasoft.ivy.Main.java
private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] confs, String mainclass, String[] args) {/*from ww w .j av a2 s . c o m*/ List urls = new ArrayList(); try { XmlReportParser parser = new XmlReportParser(); Collection all = new LinkedHashSet(); for (int i = 0; i < confs.length; i++) { Artifact[] artifacts = parser.getArtifacts(md.getModuleRevisionId().getModuleId(), confs[i], cache); all.addAll(Arrays.asList(artifacts)); } for (Iterator iter = all.iterator(); iter.hasNext();) { Artifact artifact = (Artifact) iter.next(); urls.add(ivy.getArchiveFileInCache(cache, artifact).toURL()); } } catch (Exception ex) { throw new RuntimeException("impossible to build ivy cache path: " + ex.getMessage(), ex); } URLClassLoader classLoader = new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), Main.class.getClassLoader()); try { Class c = classLoader.loadClass(mainclass); Method mainMethod = c.getMethod("main", new Class[] { String[].class }); // Split up arguments mainMethod.invoke(null, new Object[] { args }); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not find class: " + mainclass, cnfe); } catch (SecurityException e) { throw new RuntimeException("Could not find main method: " + mainclass, e); } catch (NoSuchMethodException e) { throw new RuntimeException("Could not find main method: " + mainclass, e); } catch (IllegalAccessException e) { throw new RuntimeException("No permissions to invoke main method: " + mainclass, e); } catch (InvocationTargetException e) { throw new RuntimeException("Unexpected exception invoking main method: " + mainclass, e); } }
From source file:com.aw.support.reflection.MethodInvoker.java
/** * Invoke specific method on the target and returns the value that this method returns * * @param target/*ww w.ja v a 2 s .c o m*/ * @param methodName * @return */ public static Object invoke(Object target, String methodName) throws Throwable { Object objectToReturn = null; try { Class cls = target.getClass(); Method method = cls.getMethod(methodName, null); objectToReturn = method.invoke(target, null); } catch (Throwable e) { logger.error("Cannot execute class:" + target.getClass() + "method :" + methodName); Throwable cause = e.getCause(); if ((cause instanceof FlowBreakSilentlyException) || (cause instanceof AWException)) { throw cause; } e.printStackTrace(); throw e; } return objectToReturn; }
From source file:com.hurence.logisland.util.string.StringUtilsTest.java
/** * Sets an environment variable FOR THE CURRENT RUN OF THE JVM * Does not actually modify the system's environment variables, * but rather only the copy of the variables that java has taken, * and hence should only be used for testing purposes! * @param key The Name of the variable to set * @param value The value of the variable to set *//*from www .j a va 2 s .co m*/ @SuppressWarnings("unchecked") public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException { try { /// we obtain the actual environment final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); final boolean environmentAccessibility = theEnvironmentField.isAccessible(); theEnvironmentField.setAccessible(true); final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null); if (SystemUtils.IS_OS_WINDOWS) { // This is all that is needed on windows running java jdk 1.8.0_92 if (value == null) { env.remove(key); } else { env.put((K) key, (V) value); } } else { // This is triggered to work on openjdk 1.8.0_91 // The ProcessEnvironment$Variable is the key of the map final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable"); final Method convertToVariable = variableClass.getMethod("valueOf", String.class); final boolean conversionVariableAccessibility = convertToVariable.isAccessible(); convertToVariable.setAccessible(true); // The ProcessEnvironment$Value is the value fo the map final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value"); final Method convertToValue = valueClass.getMethod("valueOf", String.class); final boolean conversionValueAccessibility = convertToValue.isAccessible(); convertToValue.setAccessible(true); if (value == null) { env.remove(convertToVariable.invoke(null, key)); } else { // we place the new value inside the map after conversion so as to // avoid class cast exceptions when rerunning this code env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value)); // reset accessibility to what they were convertToValue.setAccessible(conversionValueAccessibility); convertToVariable.setAccessible(conversionVariableAccessibility); } } // reset environment accessibility theEnvironmentField.setAccessible(environmentAccessibility); // we apply the same to the case insensitive environment final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible(); theCaseInsensitiveEnvironmentField.setAccessible(true); // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); if (value == null) { // remove if null cienv.remove(key); } else { cienv.put(key, value); } theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility); } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">", e); } catch (final NoSuchFieldException e) { // we could not find theEnvironment final Map<String, String> env = System.getenv(); Stream.of(Collections.class.getDeclaredClasses()) // obtain the declared classes of type $UnmodifiableMap .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> { try { return c1.getDeclaredField("m"); } catch (final NoSuchFieldException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + "> when locating in-class memory map of environment", e1); } }).forEach(field -> { try { final boolean fieldAccessibility = field.isAccessible(); field.setAccessible(true); // we obtain the environment final Map<String, String> map = (Map<String, String>) field.get(env); if (value == null) { // remove if null map.remove(key); } else { map.put(key, value); } // reset accessibility field.setAccessible(fieldAccessibility); } catch (final ConcurrentModificationException e1) { // This may happen if we keep backups of the environment before calling this method // as the map that we kept as a backup may be picked up inside this block. // So we simply skip this attempt and continue adjusting the other maps // To avoid this one should always keep individual keys/value backups not the entire map System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#" + field.getName() + e1); } catch (final IllegalAccessException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">. Unable to access field!", e1); } }); } System.out.println( "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key)); }
From source file:Main.java
/** * Returns attribute's setter method. If the method not found then * NoSuchMethodException will be thrown. * /*from www .jav a 2 s . co m*/ * @param cls * the class the attribute belongs to * @param attr * the attribute's name * @param type * the attribute's type * @return attribute's setter method * @throws NoSuchMethodException * if the setter was not found */ public final static Method getAttributeSetter(Class cls, String attr, Class type) throws NoSuchMethodException { StringBuffer buf = new StringBuffer(attr.length() + 3); buf.append("set"); if (Character.isLowerCase(attr.charAt(0))) { buf.append(Character.toUpperCase(attr.charAt(0))).append(attr.substring(1)); } else { buf.append(attr); } return cls.getMethod(buf.toString(), new Class[] { type }); }
From source file:es.csic.iiia.planes.behaviors.AbstractBehaviorAgent.java
@SuppressWarnings("unchecked") private static Method getMethod(Class<? extends Behavior> bClass, Class<? extends Message> mClass) { Method m = null;//from w ww.j av a 2s. co m try { m = bClass.getMethod("on", mClass); } catch (NoSuchMethodException ex) { Class c = mClass.getSuperclass(); if (Message.class.isAssignableFrom(c)) { m = getMethod(bClass, (Class<? extends Message>) c); } } catch (SecurityException ex) { LOG.log(Level.SEVERE, null, ex); } return m; }
From source file:Main.java
private static int getExifOrientation(String src) throws IOException { int orientation = 1; try {/* www . j ava 2 s . c om*/ /** * if your are targeting only api level >= 5 * ExifInterface exif = new ExifInterface(src); * orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); */ if (Build.VERSION.SDK_INT >= 5) { Class<?> exifClass = Class.forName("android.media.ExifInterface"); Constructor<?> exifConstructor = exifClass.getConstructor(new Class[] { String.class }); Object exifInstance = exifConstructor.newInstance(new Object[] { src }); Method getAttributeInt = exifClass.getMethod("getAttributeInt", new Class[] { String.class, int.class }); Field tagOrientationField = exifClass.getField("TAG_ORIENTATION"); String tagOrientation = (String) tagOrientationField.get(null); orientation = (Integer) getAttributeInt.invoke(exifInstance, new Object[] { tagOrientation, 1 }); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return orientation; }