List of usage examples for java.lang.reflect Field get
@CallerSensitive @ForceInline public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException
From source file:Main.java
public static void cleanThreadLocals(Thread thread) throws NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException { if (thread == null) return;/* w w w . j a v a2 s . co m*/ Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Class<?> threadLocalMapKlazz = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = threadLocalMapKlazz.getDeclaredField("table"); tableField.setAccessible(true); Object fieldLocal = threadLocalsField.get(thread); if (fieldLocal == null) { return; } Object table = tableField.get(fieldLocal); int threadLocalCount = Array.getLength(table); for (int i = 0; i < threadLocalCount; i++) { Object entry = Array.get(table, i); if (entry != null) { Field valueField = entry.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(entry); if (value != null) { if ("java.util.concurrent.ConcurrentLinkedQueue".equals(value.getClass().getName()) || "java.util.concurrent.ConcurrentHashMap".equals(value.getClass().getName())) { valueField.set(entry, null); } } } } }
From source file:com.ms.commons.lang.ObjectUtils.java
/** * string?trim?//from w w w.ja va 2s . co m * * @param object * @throws Exception */ private static void trimStringField(Object object, Class<?> clazz) throws Exception { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType() == String.class) { boolean isFoolback = false; if (field.isAccessible() == false) { isFoolback = true; field.setAccessible(true); } String value = (String) field.get(object); if (StringUtils.isNotEmpty(value)) { value = value.trim(); field.set(object, value); } if (isFoolback) { field.setAccessible(false); } } } }
From source file:com.ms.commons.test.common.ReflectUtil.java
public static Object getObject(Object bean, String field) { Class<?> clazz = bean.getClass(); try {//from w w w . j a v a 2s.com Field f = getDeclaredField(clazz, field); f.setAccessible(true); try { return f.get(bean); } catch (IllegalArgumentException e) { throw new UnknowException(e); } catch (IllegalAccessException e) { throw new UnknowException(e); } } catch (SecurityException e) { throw new UnknowException(e); } catch (NoSuchFieldException e) { throw new JavaFieldNotFoundException(clazz, field); } }
From source file:SigningProcess.java
public static HashMap returnCertificates() { HashMap map = new HashMap(); try {/*from ww w . j a va2 s . c om*/ providerMSCAPI = new SunMSCAPI(); Security.addProvider(providerMSCAPI); ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi"); spiField.setAccessible(true); KeyStoreSpi spi = (KeyStoreSpi) spiField.get(ks); Field entriesField = spi.getClass().getSuperclass().getDeclaredField("entries"); entriesField.setAccessible(true); Collection entries = (Collection) entriesField.get(spi); for (Object entry : entries) { alias = (String) invokeGetter(entry, "getAlias"); // System.out.println("alias :" + alias); privateKey = (Key) invokeGetter(entry, "getPrivateKey"); certificateChain = (X509Certificate[]) invokeGetter(entry, "getCertificateChain"); // System.out.println(alias + ": " + privateKey + "CERTIFICATES -----------"+Arrays.toString(certificateChain)); } map.put("privateKey", privateKey); map.put("certificateChain", certificateChain); } catch (KeyStoreException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (IOException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (NoSuchAlgorithmException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (CertificateException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (NoSuchFieldException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (SecurityException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (IllegalArgumentException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (IllegalAccessException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (NoSuchMethodException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (InvocationTargetException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } return map; }
From source file:com.browseengine.bobo.serialize.JSONSerializer.java
private static void dumpObject(JSONObject jsonObj, Field f, JSONSerializable srcObj) throws JSONSerializationException, JSONException { Object value;//from w w w . j a v a2s .c o m try { value = f.get(srcObj); } catch (Exception e) { throw new JSONSerializationException(e.getMessage(), e); } Class type = f.getType(); String name = f.getName(); if (type.isPrimitive()) { jsonObj.put(name, String.valueOf(value)); } else if (type == String.class) { if (value != null) { jsonObj.put(name, String.valueOf(value)); } } else if (JSONSerializable.class.isInstance(value)) { jsonObj.put(name, serializeJSONObject((JSONSerializable) value)); } }
From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java
/** * Get the value of the PK field//w ww . java 2 s . com * * @param <T> * @param entity * @return PK value or a String key for composite PKs */ public static <T extends BaseEntity> String getPKFieldValue(T entity) { String value = null; Field field = getPKField(entity); if (field != null) { field.setAccessible(true); Object pkValue; try { pkValue = field.get(entity); if (pkValue != null) { value = pkValue.toString(); } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new OpenStorefrontRuntimeException("Unable to get value on " + entity.getClass().getName(), "Check entity passed in."); } } else { throw new OpenStorefrontRuntimeException("Unable to find PK for enity: " + entity.getClass().getName(), "Check entity passed in."); } return value; }
From source file:com.cloudera.recordservice.tests.ClusterController.java
/** * This method allows the caller to add environment variables to the JVM. * There is no easy way to do this through a simple call, such as there is to * read env variables using System.getEnv(variableName). Much of the method * was written with guidance from stack overflow: * http://stackoverflow.com/questions//w w w .j ava2s . com * /318239/how-do-i-set-environment-variables-from-java */ protected static void setEnv(Map<String, String> newenv) { try { 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) { try { 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); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } }
From source file:com.elasticbox.jenkins.k8s.util.TestUtils.java
public static void setEnv(Map<String, String> newenv) { try {//from w w w . jav a 2 s . co 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) { try { 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.putAll(newenv); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } }
From source file:com.psiphon3.psiphonlibrary.WebViewProxySettings.java
@TargetApi(Build.VERSION_CODES.KITKAT) // for android.util.ArrayMap methods @SuppressWarnings("rawtypes") private static boolean setWebkitProxyLollipop(Context appContext, String host, int port) { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port + ""); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port + ""); try {/* w ww . j av a 2s. c om*/ Class applictionClass = Class.forName("android.app.Application"); Field mLoadedApkField = applictionClass.getDeclaredField("mLoadedApk"); mLoadedApkField.setAccessible(true); Object mloadedApk = mLoadedApkField.get(appContext); Class loadedApkClass = Class.forName("android.app.LoadedApk"); Field mReceiversField = loadedApkClass.getDeclaredField("mReceivers"); mReceiversField.setAccessible(true); ArrayMap receivers = (ArrayMap) mReceiversField.get(mloadedApk); for (Object receiverMap : receivers.values()) { for (Object receiver : ((ArrayMap) receiverMap).keySet()) { Class clazz = receiver.getClass(); if (clazz.getName().contains("ProxyChangeListener")) { Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class); Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); onReceiveMethod.invoke(receiver, appContext, intent); } } } return true; } catch (ClassNotFoundException e) { MyLog.d("Exception setting WebKit proxy on Lollipop through ProxyChangeListener: " + e.toString()); } catch (NoSuchFieldException e) { MyLog.d("Exception setting WebKit proxy on Lollipop through ProxyChangeListener: " + e.toString()); } catch (IllegalAccessException e) { MyLog.d("Exception setting WebKit proxy on Lollipop through ProxyChangeListener: " + e.toString()); } catch (NoSuchMethodException e) { MyLog.d("Exception setting WebKit proxy on Lollipop through ProxyChangeListener: " + e.toString()); } catch (InvocationTargetException e) { MyLog.d("Exception setting WebKit proxy on Lollipop through ProxyChangeListener: " + e.toString()); } return false; }
From source file:com.netflix.paas.config.base.ConfigurationProxyUtils.java
static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { // Iterate through all fields and set initial value as well as set up dynamic properties // where necessary for (final Field field : type.getFields()) { Configuration c = field.getAnnotation(Configuration.class); if (c == null) continue; String defaultValue = field.get(obj).toString(); String name = ConfigurationProxyUtils.getPropertyName(field, c); Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue, configuration);// w w w . ja v a 2 s . com field.set(obj, supplier.get()); if (field.getAnnotation(Dynamic.class) != null) { final PropertyWrapper<?> property; if (field.getType().isAssignableFrom(String.class)) { property = propertyFactory.getStringProperty(name, defaultValue); } else if (field.getType().isAssignableFrom(Integer.class)) { property = propertyFactory.getIntProperty(name, defaultValue == null ? 0 : Integer.parseInt(defaultValue)); } else if (field.getType().isAssignableFrom(Double.class)) { property = propertyFactory.getDoubleProperty(name, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)); } else if (field.getType().isAssignableFrom(Long.class)) { property = propertyFactory.getLongProperty(name, defaultValue == null ? 0L : Long.parseLong(defaultValue)); } else if (field.getType().isAssignableFrom(Boolean.class)) { property = propertyFactory.getBooleanProperty(name, defaultValue == null ? false : Boolean.parseBoolean(defaultValue)); } else { throw new RuntimeException("Unsupported type " + field.getType()); } property.addCallback(new Runnable() { @Override public void run() { try { field.set(obj, property.getValue()); } catch (Exception e) { e.printStackTrace(); } } }); } } }