List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:io.dstream.tez.utils.HadoopUtils.java
/** * *//* w w w. j av a 2 s.com*/ private static boolean generateConfigJarFromHadoopConfDir(FileSystem fs, String applicationName, List<Path> provisionedPaths, List<File> generatedJars) { boolean generated = false; String hadoopConfDir = System.getenv().get("HADOOP_CONF_DIR"); if (hadoopConfDir != null && hadoopConfDir.trim().length() > 0) { String jarFileName = ClassPathUtils.generateJarFileName("conf_"); File confDir = new File(hadoopConfDir.trim()); File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (HADOOP_CONF_DIR)"); String destinationFilePath = applicationName + "/" + jarFile.getName(); Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath); try { provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath); provisionedPaths.add(provisionedPath); generated = true; } catch (Exception e) { logger.warn("Failed to provision " + provisionedPath + "; " + e.getMessage()); if (logger.isDebugEnabled()) { logger.warn("Failed to provision " + provisionedPath, e); } throw new IllegalStateException(e); } } String tezConfDir = System.getenv().get("TEZ_CONF_DIR"); if (tezConfDir != null && tezConfDir.trim().length() > 0) { String jarFileName = ClassPathUtils.generateJarFileName("conf_tez"); File confDir = new File(tezConfDir.trim()); File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (TEZ_CONF_DIR)"); try { URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m.setAccessible(true); m.invoke(cl, jarFile.toURI().toURL()); } catch (Exception e) { throw new IllegalStateException(e); } String destinationFilePath = applicationName + "/" + jarFile.getName(); Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath); try { provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath); provisionedPaths.add(provisionedPath); generated = true; } catch (Exception e) { logger.warn("Failed to provision " + provisionedPath + "; " + e.getMessage()); if (logger.isDebugEnabled()) { logger.warn("Failed to provision " + provisionedPath, e); } throw new IllegalStateException(e); } } return generated; }
From source file:com.aw.support.reflection.MethodInvoker.java
public static Object invoke(Object target, String methodName, Object[] parameters, Class[] parameterTypes) { Object result = null;// ww w. j av a 2 s . co m try { Class cls = target.getClass(); Class[] paramTypes = parameterTypes; for (int i = 0; i < paramTypes.length; i++) { if (parameterTypes[i] == null) { paramTypes[i] = parameters[i].getClass(); } } Method method = cls.getMethod(methodName, paramTypes); method.setAccessible(true); result = method.invoke(target, parameters); } catch (Throwable e) { if (!(e instanceof AWException)) { if (e.getCause() instanceof AWException) { throw ((AWException) e.getCause()); } e.printStackTrace(); throw new AWSystemException("Problems calling the method:" + methodName, e); } else { throw (AWException) e; } } return result; }
From source file:Main.java
public static void invokeMethod(String paramString, Object paramObject, Object[] paramArrayOfObject) throws Exception { if (TextUtils.isEmpty(paramString)) throw new RuntimeException("method name can not be empty"); if (paramObject == null) throw new RuntimeException("target object can not be null"); ArrayList localArrayList = new ArrayList(); int i = paramArrayOfObject.length; for (int j = 0; j < i; j++) localArrayList.add(paramArrayOfObject[j].getClass()); Method localMethod = paramObject.getClass().getDeclaredMethod(paramString, (Class[]) localArrayList.toArray()); if (localMethod == null) throw new RuntimeException( "target object: " + paramObject.getClass().getName() + " do not have this method: " + paramString + " with parameters: " + localArrayList.toString()); localMethod.setAccessible(true); localMethod.invoke(paramObject, paramArrayOfObject); }
From source file:com.weibo.motan.demo.client.DemoRpcClient.java
public static DubboBenchmark.BenchmarkMessage prepareArgs() throws InvocationTargetException, IllegalAccessException { boolean b = true; int i = 100000; String s = "??"; DubboBenchmark.BenchmarkMessage.Builder builder = DubboBenchmark.BenchmarkMessage.newBuilder(); Method[] methods = builder.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.getName().startsWith("setField") && ((m.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC)) { Parameter[] params = m.getParameters(); if (params.length == 1) { String n = params[0].getParameterizedType().getTypeName(); m.setAccessible(true); if (n.endsWith("java.lang.String")) { m.invoke(builder, new Object[] { s }); } else if (n.endsWith("int")) { m.invoke(builder, new Object[] { i }); } else if (n.equals("boolean")) { m.invoke(builder, new Object[] { b }); }//from www . j a va2 s . c om } } } return builder.build(); }
From source file:gov.nih.nci.iso21090.hibernate.property.CollectionPropertyAccessor.java
/** * @param theClass Target class in which the value is to be set * @param propertyName Target property name * @return returns Setter class instance *///from w ww . j a va2 s .c o m @SuppressWarnings("PMD.AccessorClassGeneration") private static CollectionPropertySetter getSetterOrNull(Class theClass, String propertyName) { if (theClass == Object.class || theClass == null) { return null; } Method method = setterMethod(theClass, propertyName); if (method != null) { if (!ReflectHelper.isPublic(theClass, method)) { method.setAccessible(true); } return new CollectionPropertySetter(theClass, method, propertyName); } else { CollectionPropertySetter setter = getSetterOrNull(theClass.getSuperclass(), propertyName); if (setter == null) { Class[] interfaces = theClass.getInterfaces(); for (int i = 0; setter == null && i < interfaces.length; i++) { setter = getSetterOrNull(interfaces[i], propertyName); } } return setter; } }
From source file:fm.last.hadoop.tools.ReplicationPolicyFixer.java
public static int verifyBlockPlacement(LocatedBlock lBlk, short replication, NetworkTopology cluster) { try {/* w ww . j a v a2 s .co m*/ Class<?> replicationTargetChooserClass = Class .forName("org.apache.hadoop.hdfs.server.namenode.ReplicationTargetChooser"); Method verifyBlockPlacementMethod = replicationTargetChooserClass.getDeclaredMethod( "verifyBlockPlacement", LocatedBlock.class, Short.TYPE, NetworkTopology.class); verifyBlockPlacementMethod.setAccessible(true); return (Integer) verifyBlockPlacementMethod.invoke(null, lBlk, new Short(replication), cluster); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { cause.printStackTrace(); throw (RuntimeException) cause; } else { throw new RuntimeException(e); } } }
From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java
private static byte[] loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { String name = getOSName();/*w ww .j a v a 2 s . c o m*/ if (name == null) throw new IllegalArgumentException("Cannot determine OS"); String arch = getArch(); if (arch == null) throw new IllegalArgumentException("Cannot determine architecture"); String artifactId = "org.eclipse.swt." + name + "." + arch; String swtLocation = artifactId + "-" + SWT_VERSION + ".jar"; System.out.println("Loading SWT version " + swtLocation); byte[] data = null; File savedJar = new File(Constants.DATA_DIR, swtLocation); if (savedJar.isDirectory() && !savedJar.delete()) throw new IllegalArgumentException("Saved file is a directory and could not be deleted"); if (savedJar.exists() && savedJar.canRead()) { try { System.out.println("Loading from saved file"); InputStream inputStream = new FileInputStream(savedJar); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(inputStream, outputStream); data = outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to load from saved file."); exception.printStackTrace(System.out); } } if (data == null) { InputStream fromJar = Bootloader.class.getResourceAsStream("/swt/" + swtLocation); if (fromJar != null) { try { System.out.println("Loading from within JAR"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(fromJar, outputStream); data = outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to load within JAR"); exception.printStackTrace(System.out); } } } if (data == null) { URL url = new URL("https://maven-eclipse.github.io/maven/org/eclipse/swt/" + artifactId + "/" + SWT_VERSION + "/" + swtLocation); try { System.out.println("Loading over the internet"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() == 200) { InputStream fromURL = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(fromURL, outputStream); data = outputStream.toByteArray(); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } } catch (IOException exception) { System.out.println("Failed to load over the internet"); exception.printStackTrace(System.out); } } if (data == null) { throw new IllegalArgumentException("Failed to load SWT"); } if (!savedJar.exists()) { try { System.out.println("Writing to saved file"); if (savedJar.createNewFile()) { FileOutputStream fileOutputStream = new FileOutputStream(savedJar); fileOutputStream.write(data); fileOutputStream.close(); } else { throw new IOException("Could not create new file"); } } catch (IOException exception) { System.out.println("Failed to write to saved file"); exception.printStackTrace(System.out); } } byte[] dd = data; URL.setURLStreamHandlerFactory(protocol -> { //JarInJar! if (protocol.equals("swt")) { return new URLStreamHandler() { protected URLConnection openConnection(URL u) { return new URLConnection(u) { public void connect() { } public InputStream getInputStream() { return new ByteArrayInputStream(dd); } }; } protected void parseURL(URL u, String spec, int start, int limit) { // Don't parse or it's too slow } }; } return null; }); ClassLoader classLoader = Bootloader.class.getClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, new URL("swt://load")); return data; }
From source file:com.zigbee.framework.common.util.BeanCopyUtil.java
/** * Override copyProperties Method//from www . j a va2 s.c o m * @Date : 2011-8-5 * @param source source bean instance * @param target destination bean instance */ public static void copyProperties(Object source, Object target) { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null) { try { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); //Check whether the value is empty, only copy the properties which are not empty if (value != null) { Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } writeMethod.invoke(target, value); } } } catch (BeansException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception!" + e.getMessage(); logger.error(errMsg); } catch (SecurityException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception!" + e.getMessage(); logger.error(errMsg); } catch (IllegalArgumentException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception!" + e.getMessage(); logger.error(errMsg); } catch (IllegalAccessException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception!" + e.getMessage(); logger.error(errMsg); } catch (InvocationTargetException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception!" + e.getMessage(); logger.error(errMsg); } } } }
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 */// www . j a va2 s. c o 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:com.zigbee.framework.common.util.BeanCopyUtil.java
/** * ?/* ww w . j av a2s. com*/ * @author tun.tan * @Date 2011-9-29 ?11:18:42 */ public static void copyProps(Object source, Object target, String[] igonre) { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); Object methodName = null; // Object targetValue=null; //? for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null) { try { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (igonre != null) { boolean jump = false; // for (int i = 0; i < igonre.length; i++) { if (igonre[i] == null) {// continue; } if (targetPd.getName().equals(igonre[i])) {//? logger.info(targetPd.getName()); jump = true; } } if (jump) {// continue; } } if (sourcePd != null && sourcePd.getReadMethod() != null) {// Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); //Check whether the value is empty, only copy the properties which are not empty // targetValue=value; if (value != null) {// Method writeMethod = targetPd.getWriteMethod(); methodName = writeMethod.getName(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } writeMethod.invoke(target, value); } } } catch (BeansException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage(); logger.error(errMsg); throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause()); } catch (SecurityException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage(); logger.error(errMsg); throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause()); } catch (IllegalArgumentException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage(); logger.error(errMsg); throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause()); } catch (IllegalAccessException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage(); logger.error(errMsg); throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause()); } catch (InvocationTargetException e) { e.printStackTrace(); String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage(); logger.error(errMsg); throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause()); } } } }