List of usage examples for java.lang.reflect Field get
@CallerSensitive @ForceInline public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException
From source file:com.lidroid.xutils.utils.OtherUtils.java
/** * @param context if null, use the default format * (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30). * @return//from w ww . j av a 2s . co m */ @SuppressLint("DefaultLocale") public static String getUserAgent(Context context) { String webUserAgent = null; if (context != null) { try { Class<?> sysResCls = Class.forName("com.android.internal.R$string"); Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent"); Integer resId = (Integer) webUserAgentField.get(null); webUserAgent = context.getString(resId); } catch (Throwable ignored) { } } if (TextUtils.isEmpty(webUserAgent)) { webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1"; } Locale locale = Locale.getDefault(); StringBuffer buffer = new StringBuffer(); // Add version final String version = Build.VERSION.RELEASE; if (version.length() > 0) { buffer.append(version); } else { // default to "1.0" buffer.append("1.0"); } buffer.append("; "); final String language = locale.getLanguage(); if (language != null) { buffer.append(language.toLowerCase()); final String country = locale.getCountry(); if (country != null) { buffer.append("-"); buffer.append(country.toLowerCase()); } } else { // default to "en" buffer.append("en"); } // add the model for the release build if ("REL".equals(Build.VERSION.CODENAME)) { final String model = Build.MODEL; if (model.length() > 0) { buffer.append("; "); buffer.append(model); } } final String id = Build.ID; if (id.length() > 0) { buffer.append(" Build/"); buffer.append(id); } return String.format(webUserAgent, buffer, "Mobile "); }
From source file:com.netflix.spinnaker.orca.config.RedisConfiguration.java
@Deprecated // rz - Kept for backwards compat with old connection configs public static JedisPool createPool(GenericObjectPoolConfig redisPoolConfig, String connection, int timeout, Registry registry, String poolName) { URI redisConnection = URI.create(connection); String host = redisConnection.getHost(); int port = redisConnection.getPort() == -1 ? Protocol.DEFAULT_PORT : redisConnection.getPort(); String redisConnectionPath = isNotEmpty(redisConnection.getPath()) ? redisConnection.getPath() : "/" + DEFAULT_DATABASE; int database = Integer.parseInt(redisConnectionPath.split("/", 2)[1]); String password = redisConnection.getUserInfo() != null ? redisConnection.getUserInfo().split(":", 2)[1] : null;/*from w w w . j a v a 2s .com*/ JedisPool jedisPool = new JedisPool( redisPoolConfig != null ? redisPoolConfig : new GenericObjectPoolConfig(), host, port, timeout, password, database, null); final Field poolAccess; try { poolAccess = Pool.class.getDeclaredField("internalPool"); poolAccess.setAccessible(true); GenericObjectPool<Jedis> pool = (GenericObjectPool<Jedis>) poolAccess.get(jedisPool); registry.gauge(registry.createId("redis.connectionPool.maxIdle", "poolName", poolName), pool, (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue()); registry.gauge(registry.createId("redis.connectionPool.minIdle", "poolName", poolName), pool, (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMinIdle()).doubleValue()); registry.gauge(registry.createId("redis.connectionPool.numActive", "poolName", poolName), pool, (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getNumActive()).doubleValue()); registry.gauge(registry.createId("redis.connectionPool.numIdle", "poolName", poolName), pool, (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue()); registry.gauge(registry.createId("redis.connectionPool.numWaiters", "poolName", poolName), pool, (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue()); return jedisPool; } catch (NoSuchFieldException | IllegalAccessException e) { throw new BeanCreationException("Error creating Redis pool", e); } }
From source file:com.cat.external.util.OtherUtils.java
/** * @param context if null, use the default format * (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30). * @return//from w w w . j ava 2 s .c o m */ @SuppressLint("DefaultLocale") public static String getUserAgent(Context context) { String webUserAgent = null; if (context != null) { try { @SuppressWarnings("rawtypes") Class sysResCls = Class.forName("com.android.internal.R$string"); Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent"); Integer resId = (Integer) webUserAgentField.get(null); webUserAgent = context.getString(resId); } catch (Throwable ignored) { } } if (TextUtils.isEmpty(webUserAgent)) { webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1"; } Locale locale = Locale.getDefault(); StringBuffer buffer = new StringBuffer(); // Add version final String version = Build.VERSION.RELEASE; if (version.length() > 0) { buffer.append(version); } else { // default to "1.0" buffer.append("1.0"); } buffer.append("; "); final String language = locale.getLanguage(); if (language != null) { buffer.append(language.toLowerCase()); final String country = locale.getCountry(); if (country != null) { buffer.append("-"); buffer.append(country.toLowerCase()); } } else { // default to "en" buffer.append("en"); } // add the model for the release build if ("REL".equals(Build.VERSION.CODENAME)) { final String model = Build.MODEL; if (model.length() > 0) { buffer.append("; "); buffer.append(model); } } final String id = Build.ID; if (id.length() > 0) { buffer.append(" Build/"); buffer.append(id); } return String.format(webUserAgent, buffer, "Mobile "); }
From source file:com.frostwire.android.gui.UniversalScanner.java
private static Uri nativeScanFile(Context context, String path) { try {// w ww. j av a2 s . com File f = new File(path); Class<?> clazz = Class.forName("android.media.MediaScanner"); Constructor<?> mediaScannerC = clazz.getDeclaredConstructor(Context.class); Object scanner = mediaScannerC.newInstance(context); try { Method setLocaleM = clazz.getDeclaredMethod("setLocale", String.class); setLocaleM.invoke(scanner, Locale.US.toString()); } catch (Throwable e) { e.printStackTrace(); } Field mClientF = clazz.getDeclaredField("mClient"); mClientF.setAccessible(true); Object mClient = mClientF.get(scanner); Method scanSingleFileM = clazz.getDeclaredMethod("scanSingleFile", String.class, String.class, String.class); Uri fileUri = (Uri) scanSingleFileM.invoke(scanner, f.getAbsolutePath(), "external", "data/raw"); int n = context.getContentResolver().delete(fileUri, null, null); if (n > 0) { LOG.debug("Deleted from Files provider: " + fileUri); } Field mNoMediaF = mClient.getClass().getDeclaredField("mNoMedia"); mNoMediaF.setAccessible(true); mNoMediaF.setBoolean(mClient, false); // This is only for HTC (tested only on HTC One M8) try { Field mFileCacheF = clazz.getDeclaredField("mFileCache"); mFileCacheF.setAccessible(true); mFileCacheF.set(scanner, new HashMap<String, Object>()); } catch (Throwable e) { // no an HTC, I need some time to refactor this hack } try { Field mFileCacheF = clazz.getDeclaredField("mNoMediaPaths"); mFileCacheF.setAccessible(true); mFileCacheF.set(scanner, new HashMap<String, String>()); } catch (Throwable e) { e.printStackTrace(); } Method doScanFileM = mClient.getClass().getDeclaredMethod("doScanFile", String.class, String.class, long.class, long.class, boolean.class, boolean.class, boolean.class); Uri mediaUri = (Uri) doScanFileM.invoke(mClient, f.getAbsolutePath(), null, f.lastModified(), f.length(), false, true, false); Method releaseM = clazz.getDeclaredMethod("release"); releaseM.invoke(scanner); return mediaUri; } catch (Throwable e) { e.printStackTrace(); return null; } }
From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java
public static StringBuilder objectToCsvLine(Object gm) { StringBuilder sb = new StringBuilder(); for (Field f : getAllAtributes(gm.getClass())) { try {/*from www .j a va2s . c om*/ f.setAccessible(true); if (f.get(gm) != null) { Field idField = getIdField(f.getType()); if (idField != null) { idField.setAccessible(true); Object idValue = idField.get(f.get(gm)); sb.append(idValue.toString()); } else if (f.getType().equals(Date.class)) { sb.append(SDF.format(f.get(gm))); } else { sb.append(f.get(gm).toString()); } } } catch (Exception ex) { log.error("erro ao criar linha csv", ex); } sb.append(CSV_SEPARATOR); } sb.deleteCharAt(sb.length() - 1); sb.append(CSV_LINE_DELIMITER); return sb; }
From source file:com.ruint.core.utils.OtherUtils.java
/** * @param context/*from w w w .j ava2 s.co m*/ * if null, use the default format (Mozilla/5.0 (Linux; U; Android * %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 * %sSafari/534.30). * @return */ @SuppressWarnings("rawtypes") public static String getUserAgent(Context context) { String webUserAgent = null; if (context != null) { try { Class sysResCls = Class.forName("com.android.internal.R$string"); Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent"); Integer resId = (Integer) webUserAgentField.get(null); webUserAgent = context.getString(resId); } catch (Throwable ignored) { } } if (TextUtils.isEmpty(webUserAgent)) { webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1"; } Locale locale = Locale.getDefault(); StringBuffer buffer = new StringBuffer(); // Add version final String version = Build.VERSION.RELEASE; if (version.length() > 0) { buffer.append(version); } else { // default to "1.0" buffer.append("1.0"); } buffer.append("; "); final String language = locale.getLanguage(); if (language != null) { buffer.append(language.toLowerCase()); final String country = locale.getCountry(); if (country != null) { buffer.append("-"); buffer.append(country.toLowerCase()); } } else { // default to "en" buffer.append("en"); } // add the model for the release build if ("REL".equals(Build.VERSION.CODENAME)) { final String model = Build.MODEL; if (model.length() > 0) { buffer.append("; "); buffer.append(model); } } final String id = Build.ID; if (id.length() > 0) { buffer.append(" Build/"); buffer.append(id); } return String.format(webUserAgent, buffer, "Mobile "); }
From source file:me.totalfreedom.totalfreedommod.util.FUtil.java
@SuppressWarnings("unchecked") public static <T> T getField(Object from, String name) { Class<?> checkClass = from.getClass(); do {//from ww w. ja v a 2 s.c o m try { Field field = checkClass.getDeclaredField(name); field.setAccessible(true); return (T) field.get(from); } catch (NoSuchFieldException | IllegalAccessException ex) { } } while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null)); return null; }
From source file:com.aw.core.cache.loader.MetaLoader.java
/** * Busca en la instancia Atributos del tipo {@link com.aw.core.cache.loader.MetaLoader} *//*from w w w . j a va2 s .c om*/ static public List<MetaLoader> find(Object instance) { List<MetaLoader> list = new ArrayList<MetaLoader>(); Class cls = instance.getClass(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { try { Object value = field.get(instance); if (value instanceof MetaLoader) list.add((MetaLoader) value); } catch (IllegalAccessException e) { throw AWBusinessException.wrapUnhandledException(logger, e); } } return list; }
From source file:com.bynder.sdk.util.Utils.java
/** * Method called for each field in a query object. It extracts the different fields with * {@link ApiField} annotation and, if needed, converts it according to the conversion type * defined.//from w w w. ja v a 2 s. c o m * * @param field Field information. * @param query Query object. * @param params Parameters name/value pairs to send to the API. * * @throws IllegalAccessException If the Field object is inaccessible. */ private static void convertField(final Field field, final Object query, final Map<String, String> params) throws IllegalAccessException { field.setAccessible(true); ApiField apiField = field.getAnnotation(ApiField.class); if (field.get(query) != null && apiField != null) { if (apiField.conversionType() == ConversionType.NONE) { params.put(apiField.name(), field.get(query).toString()); } else { if (apiField.conversionType() == ConversionType.METAPROPERTY_FIELD) { MetapropertyField metapropertyField = (MetapropertyField) field.get(query); params.put(String.format("%s.%s", apiField.name(), metapropertyField.getMetapropertyId()), StringUtils.join(metapropertyField.getOptionsIds(), Utils.STR_COMMA)); } else if (apiField.conversionType() == ConversionType.LIST_FIELD) { List<?> listField = (List<?>) field.get(query); params.put(apiField.name(), StringUtils.join(listField, Utils.STR_COMMA)); } } } field.setAccessible(false); }
From source file:com.sixt.service.framework.servicetest.helper.DockerComposeHelper.java
@SuppressWarnings("unchecked") private static void setEnv(Map<String, String> newEnv) { try {/*from www . j a v 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.clear(); map.putAll(newEnv); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } }