List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:net.kamhon.ieagle.util.VoUtil.java
/** * To upperCase object String field/*from w w w .j a v a 2 s . c o m*/ * * @param all * default is false. true means toUpperCase all String field, false toUpperCase the fields have * net.kamhon.ieagle.vo.core.annotation.ToUpperCase. * * @param objects */ public static void toUpperCaseProperties(boolean all, Object... objects) { for (Object object : objects) { if (object == null) { continue; } // getter for String field only Map<String, Method> getterMap = new HashMap<String, Method>(); // setter for String field only Map<String, Method> setterMap = new HashMap<String, Method>(); Class<?> clazz = object.getClass(); Method[] methods = clazz.getMethods(); for (Method method : methods) { /* * log.debug("method = " + method.getName()); * log.debug("method.getParameterTypes().length = " + * method.getParameterTypes().length); if * (method.getParameterTypes().length == 1) * log.debug("method.getParameterTypes()[0] = " + * method.getParameterTypes()[0]); * log.debug("method.getReturnType() = " + * method.getReturnType()); * log.debug("=================================================" * ); */ if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 && method.getReturnType().equals(String.class)) { // if method name is getXxx String fieldName = method.getName().substring(3); fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); getterMap.put(fieldName, method); } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == String.class && method.getReturnType().equals(void.class)) { // log.debug("setter = " + method.getName()); // if method name is setXxx String fieldName = method.getName().substring(3); fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); setterMap.put(fieldName, method); } } // if the key exists in both getter & setter for (String key : getterMap.keySet()) { if (setterMap.containsKey(key)) { try { Method getterMethod = getterMap.get(key); Method setterMethod = setterMap.get(key); // if not all, check on Field if (!all) { Field field = null; Class<?> tmpClazz = clazz; // looping up to superclass to get decleared field do { try { field = tmpClazz.getDeclaredField(key); } catch (Exception ex) { // do nothing } if (field != null) { break; } tmpClazz = tmpClazz.getSuperclass(); } while (tmpClazz != null); ToUpperCase toUpperCase = field.getAnnotation(ToUpperCase.class); if (toUpperCase == null || toUpperCase.upperCase() == false) { continue; } } String value = (String) getterMethod.invoke(object, new Object[] {}); if (StringUtils.isNotBlank(value)) setterMethod.invoke(object, value.toUpperCase()); } catch (Exception ex) { // log.error("Getter Setter for " + key + " has error ", ex); } } } } }
From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java
/** * Parse the RetryPolicy policy.// w w w.j a va2s. co m */ public static RetryPolicy parseRetryPolicy(String retryPolicyString) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException { if (!retryPolicyString.contains(".")) { retryPolicyString = "com.datastax.driver.core.policies." + retryPolicyString; Class<?> clazz = Class.forName(retryPolicyString); Field field = clazz.getDeclaredField("INSTANCE"); RetryPolicy policy = (RetryPolicy) field.get(null); return policy; } return null; }
From source file:com.datatorrent.stram.support.StramTestSupport.java
public static void setEnv(Map<String, String> newenv) throws Exception { try {//from w w w.ja v a 2s . c o m Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } }
From source file:com.app.server.util.ClassLoaderUtil.java
public static boolean cleanupJarFileFactory(CopyOnWriteArrayList setJarFileNames2Close) { boolean res = false; Class classJarURLConnection = null; try {//w w w .ja v a 2 s. c o m classJarURLConnection = Class.forName("sun.net.www.protocol.jar.JarURLConnection"); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (classJarURLConnection == null) { return res; } Field f = null; try { f = classJarURLConnection.getDeclaredField("factory"); } catch (NoSuchFieldException e) { e.printStackTrace(); } if (f == null) { return res; } f.setAccessible(true); Object obj = null; try { obj = f.get(null); } catch (IllegalAccessException e) { // ignore } if (obj == null) { return res; } Class classJarFileFactory = obj.getClass(); // HashMap fileCache = null; try { f = classJarFileFactory.getDeclaredField("fileCache"); f.setAccessible(true); obj = f.get(null); if (obj instanceof HashMap) { fileCache = (HashMap) obj; } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } HashMap urlCache = null; try { f = classJarFileFactory.getDeclaredField("urlCache"); f.setAccessible(true); obj = f.get(null); if (obj instanceof HashMap) { urlCache = (HashMap) obj; } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (urlCache != null) { HashMap urlCacheTmp = (HashMap) urlCache.clone(); Iterator it = urlCacheTmp.keySet().iterator(); while (it.hasNext()) { obj = it.next(); if (!(obj instanceof JarFile)) { continue; } JarFile jarFile = (JarFile) obj; if (setJarFileNames2Close.contains(jarFile.getName().trim().toUpperCase())) { try { jarFile.close(); } catch (IOException e) { e.printStackTrace(); } if (fileCache != null) { fileCache.remove(jarFile); } urlCache.remove(jarFile); } } res = true; } else if (fileCache != null) { // urlCache := null HashMap fileCacheTmp = (HashMap) fileCache.clone(); Iterator it = fileCacheTmp.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); obj = fileCache.get(key); if (!(obj instanceof JarFile)) { continue; } JarFile jarFile = (JarFile) obj; try { jarFile.close(); } catch (IOException e) { // ignore } fileCache.remove(key); } res = true; } setJarFileNames2Close.clear(); return res; }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static Field findField(Class<?> type, String fieldName) throws NoSuchFieldException, SecurityException { if (type.equals(Object.class)) { return type.getDeclaredField(fieldName); }/*ww w . j av a 2 s . c om*/ // now that's an ugly construct :) Field field = null; try { field = type.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { field = findField(type.getSuperclass(), fieldName); } return field; }
From source file:gov.nih.nci.caarray.dao.SampleDaoImpl.java
private static String getDiscriminator(Class<? extends AbstractBioMaterial> bmClass) { String errorMsg = "Not a valid biomaterial class (no DISCRIMINATOR field): "; try {//from w w w . ja va2s.c o m Field discField = bmClass.getDeclaredField("DISCRIMINATOR"); return (String) discField.get(null); } catch (SecurityException e) { throw new IllegalArgumentException(errorMsg + bmClass, e); } catch (NoSuchFieldException e) { throw new IllegalArgumentException(errorMsg + bmClass, e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(errorMsg + bmClass, e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(errorMsg + bmClass, e); } }
From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java
private static void clearRmiLoaderHandler(ClassLoader classLoader) { // HACK: Clear it from the RMI class loader as well // We can safely remove this since we no longer have this class loader around // and the table key is based on the class loader try {/* ww w . j a v a 2 s . c o m*/ final Class<?> loaderHandlerClass = classLoader.loadClass("sun.rmi.server.LoaderHandler"); synchronized (loaderHandlerClass) { Field loadTableField = loaderHandlerClass.getDeclaredField("loaderTable"); loadTableField.setAccessible(true); Map<?, ?> loaderTable = (Map<?, ?>) loadTableField.get(null); for (Iterator it = loaderTable.entrySet().iterator(); it.hasNext();) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next(); Object loaderKey = entry.getKey(); Field parentField = loaderKey.getClass().getDeclaredField("parent"); parentField.setAccessible(true); if (parentField.get(loaderKey) == classLoader) { it.remove(); } } } } catch (Throwable t) { // ignore } }
From source file:eu.vital.vitalcep.restApp.alert.Alerts.java
public static int getPid(Process process) { try {/*from w w w .j a v a 2s .co m*/ Class<?> cProcessImpl = process.getClass(); java.lang.reflect.Field fPid = cProcessImpl.getDeclaredField("pid"); if (!fPid.isAccessible()) { fPid.setAccessible(true); } return fPid.getInt(process); } catch (Exception e) { return -1; } }
From source file:Mopex.java
/** * Finds the first (from the bottom of the inheritance hierarchy) field with * the specified name. Note that Class.getField returns only public fields. * //from ww w. ja v a2 s . co m * @return Field * @param cls * java.lang.Class * @param name * String */ //start extract findField public static Field findField(Class cls, String name) throws NoSuchFieldException { if (cls != null) { try { return cls.getDeclaredField(name); } catch (NoSuchFieldException e) { return findField(cls.getSuperclass(), name); } } else { throw new NoSuchFieldException(); } }
From source file:com.oneis.javascript.Runtime.java
private static void checkJavaScriptTimeZoneIsGMT() { // Check that the timezone is GMT - datetime.js has created a Date object to run static initializers. // This is specific to the exact version of the Rhino implementation, but should fail gracefully if it's changed. boolean nativeDateTimeZoneOK = false; try {/* w ww . j a v a 2 s . c o m*/ java.lang.Class nativeDate = java.lang.Class.forName("org.mozilla.javascript.NativeDate"); java.lang.reflect.Field nativeDateTimeZoneField = nativeDate.getDeclaredField("thisTimeZone"); nativeDateTimeZoneField.setAccessible(true); java.util.TimeZone tz = (java.util.TimeZone) nativeDateTimeZoneField.get(null); java.lang.reflect.Field nativeDateLocalTZAField = nativeDate.getDeclaredField("LocalTZA"); nativeDateLocalTZAField.setAccessible(true); if (tz != null && (tz.getID().equals("GMT0") || tz.getID().equals("GMT") || tz.getID().equals("UTC")) && nativeDateLocalTZAField.getDouble(null) == 0.0) { nativeDateTimeZoneOK = true; } } catch (Exception e) { // Ignore, nativeDateTimeZoneOK won't be set to true. } if (!nativeDateTimeZoneOK) { System.out.println("\n\nThe operating system's time zone must be set to GMT (GMT0 Java TimeZone).\n"); throw new RuntimeException("JavaScript interpreter's local time zone is not GMT (GMT0 Java TimeZone)."); } }