List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java
/** * Hack to disable crypto restrictions until Java 9 is out. * * See http://stackoverflow.com/a/22492582/2672392 *///from w ww.j a v a 2 s . c o m public static void removeRestrictions() { try { Class<?> jceSecurityClass = Class.forName("javax.crypto.JceSecurity"); Class<?> cryptoPermissionsClass = Class.forName("javax.crypto.CryptoPermissions"); Class<?> cryptoAllPermissionClass = Class.forName("javax.crypto.CryptoAllPermission"); Field isRestrictedField = jceSecurityClass.getDeclaredField("isRestricted"); isRestrictedField.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL); isRestrictedField.set(null, false); Field defaultPolicyField = jceSecurityClass.getDeclaredField("defaultPolicy"); defaultPolicyField.setAccessible(true); PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null); Field permsField = cryptoPermissionsClass.getDeclaredField("perms"); permsField.setAccessible(true); ((Map<?, ?>) permsField.get(defaultPolicy)).clear(); Field cryptoAllPermissionInstanceField = cryptoAllPermissionClass.getDeclaredField("INSTANCE"); cryptoAllPermissionInstanceField.setAccessible(true); defaultPolicy.add((Permission) cryptoAllPermissionInstanceField.get(null)); } catch (Exception e) { // ignore } }
From source file:com.facebook.presto.hive.s3.TestPrestoS3FileSystem.java
@SuppressWarnings("unchecked") private static <T> T getFieldValue(Object instance, Class<?> clazz, String name, Class<T> type) { try {// w w w . ja v a 2 s . c o m Field field = clazz.getDeclaredField(name); checkArgument(field.getType() == type, "expected %s but found %s", type, field.getType()); field.setAccessible(true); return (T) field.get(instance); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } }
From source file:Main.java
/** * Swing menus are looking pretty bad on Linux when the GTK LaF is used (See * bug #6925412). It will most likely never be fixed anytime soon so this * method provides a workaround for it. It uses reflection to change the GTK * style objects of Swing so popup menu borders have a minimum thickness of * 1 and menu separators have a minimum vertical thickness of 1. *//*w w w. ja v a2 s . c o m*/ public static void installGtkPopupBugWorkaround() { // Get current look-and-feel implementation class LookAndFeel laf = UIManager.getLookAndFeel(); Class<?> lafClass = laf.getClass(); // Do nothing when not using the problematic LaF if (!lafClass.getName().equals("com.sun.java.swing.plaf.gtk.GTKLookAndFeel")) return; // We do reflection from here on. Failure is silently ignored. The // workaround is simply not installed when something goes wrong here try { // Access the GTK style factory Field field = lafClass.getDeclaredField("styleFactory"); boolean accessible = field.isAccessible(); field.setAccessible(true); Object styleFactory = field.get(laf); field.setAccessible(accessible); // Fix the horizontal and vertical thickness of popup menu style Object style = getGtkStyle(styleFactory, new JPopupMenu(), "POPUP_MENU"); fixGtkThickness(style, "yThickness"); fixGtkThickness(style, "xThickness"); // Fix the vertical thickness of the popup menu separator style style = getGtkStyle(styleFactory, new JSeparator(), "POPUP_MENU_SEPARATOR"); fixGtkThickness(style, "yThickness"); } catch (Exception e) { // Silently ignored. Workaround can't be applied. } }
From source file:net.kamhon.ieagle.util.VoUtil.java
private static Field getFieldForNotNestedProperty(Object obj, String propertyName) { Field field = null;/* ww w . j a v a2 s . c o m*/ Class<?> tmpClazz = obj.getClass(); // looping up to superclass to get decleared field do { try { field = tmpClazz.getDeclaredField(propertyName); } catch (Exception ex) { } if (field != null) { break; } tmpClazz = tmpClazz.getSuperclass(); } while (tmpClazz != null); return field; }
From source file:IntrospectionUtil.java
public static Field findField(Class clazz, String targetName, Class targetType, boolean checkInheritance, boolean strictType) throws NoSuchFieldException { if (clazz == null) throw new NoSuchFieldException("No class"); if (targetName == null) throw new NoSuchFieldException("No field name"); try {// www . jav a 2 s . c o m Field field = clazz.getDeclaredField(targetName); if (strictType) { if (field.getType().equals(targetType)) return field; } else { if (field.getType().isAssignableFrom(targetType)) return field; } if (checkInheritance) { return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName, targetType, strictType); } else throw new NoSuchFieldException("No field with name " + targetName + " in class " + clazz.getName() + " of type " + targetType); } catch (NoSuchFieldException e) { return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName, targetType, strictType); } }
From source file:com.bt.download.android.gui.UniversalScanner.java
private static Uri nativeScanFile(Context context, String path) { try {/*from 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); 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 } 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:com.xhsoft.framework.common.utils.ReflectUtil.java
/** * <p>Description:setFieldValue</p> * @param target/* ww w.j a v a 2 s.co m*/ * @param fname * @param ftype * @param fvalue * @return void */ @SuppressWarnings("unchecked") public static void setFieldValue(Object target, String fname, Class ftype, Object fvalue) { if (target == null || fname == null || "".equals(fname) || (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass()))) { return; } Class clazz = target.getClass(); try { Method method = clazz .getDeclaredMethod("set" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), ftype); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } method.invoke(target, fvalue); } catch (Exception me) { try { Field field = clazz.getDeclaredField(fname); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } field.set(target, fvalue); } catch (Exception fe) { if (logger.isDebugEnabled()) { logger.debug(fe); } } } }
From source file:com.github.dozermapper.core.util.ReflectionUtils.java
private static Field getFieldFromBean(Class<?> clazz, String fieldName, final Class<?> originalClass) { try {//from w w w.ja va2 s . c o m Field field = clazz.getDeclaredField(fieldName); // Allow access to private instance var's that dont have public setter. field.setAccessible(true); return field; } catch (NoSuchFieldException e) { if (clazz.getSuperclass() != null) { return getFieldFromBean(clazz.getSuperclass(), fieldName, originalClass); } throw new MappingException("No such field found " + originalClass.getName() + "." + fieldName, e); } }
From source file:com.github.fcannizzaro.resourcer.Resourcer.java
/** * Parse values xml files/*from w ww. ja v a2 s. c o m*/ */ private static void findValues() { values = new HashMap<>(); File dir = new File(PATH_BASE + VALUES_DIR); if (!dir.isDirectory()) return; File[] files = dir.listFiles(); if (files == null) return; for (File file : files) // only *.xml files if (file.getName().matches(".*\\.xml$")) { Document doc = FileUtils.readXML(file.getAbsolutePath()); if (doc == null) return; Element ele = doc.getDocumentElement(); for (String element : elements) { NodeList list = ele.getElementsByTagName(element); if (values.get(element) == null) values.put(element, new HashMap<>()); for (int j = 0; j < list.getLength(); j++) { Element node = (Element) list.item(j); String value = node.getFirstChild().getNodeValue(); Object valueDefined = value; switch (element) { case INTEGER: valueDefined = Integer.valueOf(value); break; case DOUBLE: valueDefined = Double.valueOf(value); break; case FLOAT: valueDefined = Float.valueOf(value); break; case BOOLEAN: valueDefined = Boolean.valueOf(value); break; case LONG: valueDefined = Long.valueOf(value); break; case COLOR: if (value.matches("@color/.*")) { try { Class<?> c = Class.forName("com.github.fcannizzaro.material.Colors"); Object colors = c.getDeclaredField(value.replace("@color/", "")).get(c); Method asColor = c.getMethod("asColor"); valueDefined = asColor.invoke(colors); } catch (Exception e) { System.out.println("ERROR Resourcer - Cannot bind " + value); } } else valueDefined = Color.decode(value); break; } values.get(node.getNodeName()).put(node.getAttribute("name"), valueDefined); } } } }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
public static void setFinalField(Class<?> clazz, Object obj, String fieldName, Object value) throws NoSuchFieldException { Field field = clazz.getDeclaredField(fieldName); setFinalField(obj, field, value);//from w w w . j av a2 s . c om }