List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:com.tobedevoured.naether.NaetherTest.java
private static void setEnv(Map<String, String> newenv) { try {/*ww w.java2 s. c om*/ 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:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java
/** * @param screenWidth the with of the screen * @param runnables {@link ArrayList} of available runnables. *//* w w w . jav a 2 s.co m*/ private static void printAvailableRunnables(int screenWidth, ArrayList<Class<? extends SOMToolboxApp>> runnables) { Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR); ArrayList<Class<? extends SOMToolboxApp>> runnableClassList = new ArrayList<Class<? extends SOMToolboxApp>>(); ArrayList<String> runnableNamesList = new ArrayList<String>(); ArrayList<String> runnableDeskrList = new ArrayList<String>(); for (Class<? extends SOMToolboxApp> c : runnables) { try { // Ignore abstract classes and interfaces if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { continue; } runnableClassList.add(c); runnableNamesList.add(c.getSimpleName()); String desk = null; try { Field f = c.getDeclaredField("DESCRIPTION"); desk = (String) f.get(null); } catch (Exception e) { } if (desk != null) { runnableDeskrList.add(desk); } else { runnableDeskrList.add(""); } } catch (SecurityException e) { // Should not happen - no Security } catch (IllegalArgumentException e) { e.printStackTrace(); } } StringBuilder sb = new StringBuilder(); String lineSep = System.getProperty("line.separator", "\n"); int maxLen = StringUtils.getLongestStringLength(runnableNamesList); sb.append("Runnable classes:").append(lineSep); for (int i = 0; i < runnableNamesList.size(); i++) { final Type cType = Type.getType(runnableClassList.get(i)); if (i == 0 || !cType.equals(Type.getType(runnableClassList.get(i - 1)))) { sb.append(String.format("-- %s %s%s", cType.toString(), StringUtils.repeatString(screenWidth - (8 + cType.toString().length()), "-"), lineSep)); } sb.append(" "); sb.append(runnableNamesList.get(i)); sb.append(StringUtils.getSpaces(4 + maxLen - runnableNamesList.get(i).length())).append("- "); sb.append(runnableDeskrList.get(i)); sb.append(lineSep); } System.out.println(StringUtils.wrap(sb.toString(), screenWidth, StringUtils.getSpaces(maxLen + 10), true)); }
From source file:com.haulmont.cuba.web.gui.components.WebComponentsHelper.java
/** * @deprecated use the {@link Icons#get(com.haulmont.cuba.gui.icons.Icons.Icon)} bean * and {@link com.haulmont.cuba.gui.icons.CubaIcon} icon set instead *//*from w w w . j a v a2 s. c o m*/ @Deprecated @Nullable public static Resource getFontIconResource(String fontIconName, String fontIconField) throws NoSuchFieldException, IllegalAccessException { final Class<? extends FontIcon> fontIcon = fontIcons.get(fontIconName); if (fontIcon != null) { Field field = fontIcon.getDeclaredField(fontIconField); return (Resource) field.get(null); } return null; }
From source file:com.jk.util.JKObjectUtil.java
/** * Gets the field value.//from w ww . j a va 2s . c om * * @param <T> * the generic type * @param clas * the clas * @param instance * the instance * @param fieldName * the field name * @return the field value */ public static <T> T getFieldValue(Class<?> clas, Object instance, String fieldName) { try { Field declaredField = clas.getDeclaredField(fieldName); declaredField.setAccessible(true); return (T) declaredField.get(instance); } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { throw new JKException(e); } }
From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java
public static Field getField(Class<?> cl, String field_name) { try {/* w w w .java 2 s .c o m*/ return cl.getDeclaredField(field_name); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return null; }
From source file:org.jdbcluster.JDBClusterUtil.java
/** * returns Field object for Properties. Iterates over all superclasses Find * a Field with the given Field name and the given parameter types, declared * on the given class or one of its superclasses. Will return a protected, * package access, or private Field too. * <p>/*from w w w. jav a2 s . c o m*/ * Checks <code>getDeclaredField</code>. * * @param propName * path to property * @param c * Class object * @return Field instance */ static public Field getDeclaredField(String propName, Class clazz) { Assert.notNull(clazz, "clazz may not be null"); Assert.hasLength(propName, "obj may not be null or \"\""); Field f = null; try { f = clazz.getDeclaredField(propName); } catch (SecurityException e) { throw new ConfigurationException( "cant get field for property [" + propName + "] with the specified name for " + clazz.getName(), e); } catch (NoSuchFieldException e) { if (clazz.getSuperclass() != null) { return JDBClusterUtil.getDeclaredField(propName, clazz.getSuperclass()); } throw new ConfigurationException("cant get field for property [" + propName + "] with the specified name for " + clazz.getName(), e); } return f; }
From source file:com.us.reflect.ClassFinder.java
/** * ?// w w w. j a v a2 s . co m * * @param container * @param parnames ? * @return * @throws SecurityException * @throws NoSuchFieldException */ private static Class<?>[] findParameterTypes(Class<?> container, String[] parnames) throws SecurityException, NoSuchFieldException { List<Class<?>> parames = new LinkedList<Class<?>>(); for (String param : parnames) { char index0 = param.charAt(0); String filed = param.substring(1); if (index0 == '#') { parames.add(Object.class); } else if (index0 == '@' && filed.equals("request")) { parames.add(HttpServletRequest.class); } else if (index0 == '@' && filed.equals("response")) { parames.add(HttpServletResponse.class); } else if (index0 == '$') { parames.add(container.getDeclaredField(filed).getType()); } else { parames.add(container.getDeclaredField(param).getType()); } } return parames.toArray(new Class<?>[] {}); }
From source file:com.frostwire.android.gui.UniversalScanner.java
private static Uri nativeScanFile(Context context, String path) { try {//from w w w.j a v a2s . c o m 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:io.apiman.manager.api.es.EsMarshallingTest.java
/** * Fabricates a new instance of the given bean type. Uses reflection to figure * out all the fields and assign generated values for each. */// w ww .j ava 2s . co m private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { T bean = beanClass.newInstance(); Map<String, String> beanProps = BeanUtils.describe(bean); for (String key : beanProps.keySet()) { try { Field declaredField = beanClass.getDeclaredField(key); Class<?> fieldType = declaredField.getType(); if (fieldType == String.class) { BeanUtils.setProperty(bean, key, StringUtils.upperCase(key)); } else if (fieldType == Boolean.class || fieldType == boolean.class) { BeanUtils.setProperty(bean, key, Boolean.TRUE); } else if (fieldType == Date.class) { BeanUtils.setProperty(bean, key, new Date(1)); } else if (fieldType == Long.class || fieldType == long.class) { BeanUtils.setProperty(bean, key, 17L); } else if (fieldType == Integer.class || fieldType == long.class) { BeanUtils.setProperty(bean, key, 11); } else if (fieldType == Set.class) { // Initialize to a linked hash set so that order is maintained. BeanUtils.setProperty(bean, key, new LinkedHashSet()); Type genericType = declaredField.getGenericType(); String typeName = genericType.getTypeName(); String typeClassName = typeName.substring(14, typeName.length() - 1); Class<?> typeClass = Class.forName(typeClassName); Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key); populateSet(collection, typeClass); } else if (fieldType == Map.class) { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("KEY-1", "VALUE-1"); map.put("KEY-2", "VALUE-2"); BeanUtils.setProperty(bean, key, map); } else if (fieldType.isEnum()) { BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]); } else if (fieldType.getPackage() != null && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) { Object childBean = createBean(fieldType); BeanUtils.setProperty(bean, key, childBean); } else { throw new IllegalAccessException( "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName()); } // String capKey = StringUtils.capitalize(key); // System.out.println(key);; } catch (NoSuchFieldException e) { // Skip it - there is not really a bean property with this name! } } return bean; }
From source file:com.screenslicer.common.CommonUtil.java
public static void setMethod(HttpURLConnection httpURLConnection, String method) { try {/*from w w w . j a v a 2s. co m*/ httpURLConnection.setRequestMethod(method); // Check whether we are running on a buggy JRE } catch (final ProtocolException pe) { Class<?> connectionClass = httpURLConnection.getClass(); Field delegateField = null; try { delegateField = connectionClass.getDeclaredField("delegate"); delegateField.setAccessible(true); HttpURLConnection delegateConnection = (HttpURLConnection) delegateField.get(httpURLConnection); setMethod(delegateConnection, method); } catch (NoSuchFieldException e) { // Ignore for now, keep going } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } try { Field methodField; while (connectionClass != null) { try { methodField = connectionClass.getDeclaredField("method"); } catch (NoSuchFieldException e) { connectionClass = connectionClass.getSuperclass(); continue; } methodField.setAccessible(true); methodField.set(httpURLConnection, method); break; } } catch (final Exception e) { throw new RuntimeException(e); } } }