List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java
/** * This method will use to know about the IO Stream is closed or Open. * There some issue in ZipInputStream.getNextEntry() some time its throws Exception of 'stream close' instead of return null. * So this is a method will get private field [closed] of InputStream class so program could know that stream is open or closed. * @return boolean/*from w w w. j ava 2 s .co m*/ * It will return true if stream is closed else return false */ private boolean isStreamClose(ZipInputStream inStream) { try { Class c = inStream.getClass(); Field in; in = c.getDeclaredField("closed"); in.setAccessible(true); Boolean inReader = (Boolean) in.get(inStream); return inReader; } catch (Exception e) { logger.error(e); } return false; }
From source file:jef.tools.security.EncrypterUtil.java
/** * ???// w w w .j ava 2 s . c o m * @return */ public static boolean removeCryptographyRestrictions() { if (!isRestrictedCryptography()) { return false; } try { /* * Do the following, but with reflection to bypass access checks: * * JceSecurity.isRestricted = false; * JceSecurity.defaultPolicy.perms.clear(); * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE); */ final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity"); final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions"); final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission"); final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted"); isRestrictedField.setAccessible(true); final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL); isRestrictedField.set(null, false); final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy"); defaultPolicyField.setAccessible(true); final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null); final Field perms = cryptoPermissions.getDeclaredField("perms"); perms.setAccessible(true); ((Map<?, ?>) perms.get(defaultPolicy)).clear(); final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE"); instance.setAccessible(true); defaultPolicy.add((Permission) instance.get(null)); return true; } catch (final Exception e) { LogUtil.error("Failed to remove cryptography restrictions", e); return false; } }
From source file:mseries.nvspycamera.PinConfigurer.java
protected GpioPinDigital getPin(String gpioName, String name, String type, String value) { Pin raspiPin = null;//from ww w. j a v a 2 s . co m GpioPinDigital pin; logger.debug(gpioName + ", " + name + ", " + type + ", " + value); try { Class<?> c = Class.forName("com.pi4j.io.gpio.RaspiPin"); Field f = c.getDeclaredField(gpioName); raspiPin = (Pin) f.get(null); switch (type) { case "INPUT": c = Class.forName("com.pi4j.io.gpio.PinPullResistance"); f = c.getDeclaredField(value); pin = gpioController.provisionDigitalInputPin(raspiPin, name, (PinPullResistance) f.get(null)); pin.setShutdownOptions(true, PinState.LOW, PinPullResistance.OFF); return pin; case "OUTPUT": c = Class.forName("com.pi4j.io.gpio.PinState"); f = c.getDeclaredField(value); pin = gpioController.provisionDigitalOutputPin(raspiPin, name, (PinState) f.get(null)); pin.setShutdownOptions(true, PinState.LOW); return pin; default: logger.error("Type code:" + type + " is not valid"); } } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); } return null; }
From source file:org.spring.data.gemfire.config.DiskStoreBeanPostProcessor.java
@SuppressWarnings("unchecked") private <T> T readField(final Object obj, final String fieldName) { try {/* w w w . ja v a2 s .co m*/ Class type = obj.getClass(); Field field; do { field = type.getDeclaredField(fieldName); type = type.getSuperclass(); } while (field == null && !Object.class.equals(type)); if (field == null) { throw new NoSuchFieldException( String.format("Field (%1$s) does not exist on Object of Class type (%2$s)!", fieldName, ObjectUtils.nullSafeClassName(obj))); } field.setAccessible(true); return (T) field.get(obj); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.codehaus.griffon.commons.GriffonClassUtils.java
/** * <p>Work out if the specified property is readable and static. Java introspection does not * recognize this concept of static properties but Groovy does. We also consider public static fields * as static properties with no getters/setters</p> * * @param clazz The class to check for static property * @param propertyName The property name * @return true if the property with name propertyName has a static getter method */// ww w . j a v a2 s . co m public static boolean isStaticProperty(Class clazz, String propertyName) { Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(propertyName), null); if (getter != null) { return isPublicStatic(getter); } else { try { Field f = clazz.getDeclaredField(propertyName); if (f != null) { return isPublicStatic(f); } } catch (NoSuchFieldException e) { return false; } } return false; }
From source file:com.industrieit.ohr.OHRJavassister.java
public static Class ohr(Class cll) { try {//from w w w . j a va 2 s.c o m //System.out.println("++++++++++ "+cll.getName()); /*if (cll.getName().startsWith("ohr.")) { throw new RuntimeException(cll.getName()); }*/ if (processed2.containsKey(cll)) { return processed2.get(cll); } HashSet<Long> handleOffsets = new HashSet<Long>(); String cnam = cll.getName(); if (!cnam.startsWith("ohr.")) { cnam = "ohr." + cll.getName(); //cnam=cnam.substring(4); } Class cl = Class.forName(cnam.substring(4)); int clnumber = incrementClsCounter(); List<Integer> owned = new ArrayList<Integer>(); //remove the old implementation if its around from another process String fname = "target/classes/" + cnam.replace(".", "/") + ".class"; System.out.println("deleted" + fname + " " + (new File(fname).delete())); if (!Modifier.isAbstract(cl.getModifiers())) { throw new RuntimeException("not an abstract class " + cl.getName()); } System.out.println("processing ohr " + cnam); CtClass bc = getDefault().getCtClass(cl.getName()); CtClass cc = getDefault().makeClass(cnam, bc); StringBuilder initBuilder = new StringBuilder(); initBuilder.append("public void internalInit() {\n"); StringBuilder constructBuilder = new StringBuilder(); constructBuilder.append("{"); String intname = OHRBase.class.getName(); System.out.println("intername is " + intname); CtClass ci = getDefault().getCtClass(intname); CtClass extern = getDefault().getCtClass(Externalizable.class.getName()); //cc.addInterface(ci); cc.setInterfaces(new CtClass[] { ci, extern }); cc.setSuperclass(bc); //add base implmenetation methods and properties setBaseMixinsPre(cc, false); //first long for id and other stuff long offset = 8; BeanInfo bi = Introspector.getBeanInfo(cl); PropertyDescriptor[] pds = bi.getPropertyDescriptors(); for (int co = 0; co < propertyOrdering.length; co++) { Class cprop = propertyOrdering[co]; for (int i = 0; i < pds.length; i++) { // Get property name String propName = pds[i].getName(); if (propName.equals("class")) { continue; } String typ = pds[i].getPropertyType().getName(); Class type = pds[i].getPropertyType(); //if (propName.startsWith("fath")) //PL.pl("[[[[["+type+" "+propName+" "+cprop); if (cprop == Object.class) { //handle refs only if (type.isPrimitive()) { continue; } if (type == String.class) { continue; } if (type == CharSequence.class) { continue; } if (type == OHRLongArray.class) { continue; } if (type == OHRIntArray.class) { continue; } if (type == OHRShortArray.class) { continue; } if (type == OHRByteArray.class) { continue; } if (type == OHRBooleanArray.class) { continue; } if (type == OHRDoubleArray.class) { continue; } if (type == OHRFloatArray.class) { continue; } } else if (cprop != type) { //PL.pl("skipping "+type+" "+cprop); continue; } //PL.pl("[[[[[ " + type + " - " + propName + " - " + cprop); //System.out.println("--prop--" + propName); String rname = pds[i].getReadMethod().getName(); String wname = null; if (pds[i].getWriteMethod() != null) { wname = pds[i].getWriteMethod().getName(); } boolean reifread = isMethodReifAnnotated(pds[i].getReadMethod()); boolean reifwrite = isMethodReifAnnotated(pds[i].getWriteMethod()); String wcons = getConsistencyAsString(pds[i].getWriteMethod()); String rcons = getConsistencyAsString(pds[i].getReadMethod()); System.out.println("TYPE " + pds[i].getPropertyType().getName() + " " + pds[i].getPropertyType().getInterfaces()); if (pds[i].getPropertyType() == String.class && isInlineString(pds[i])) { //NOTE - only for inline strings - normal strings are handled as extrefs like any other object System.out.println("ITS An inline string!!!!"); int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length(); boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class) .trimOverflow(); boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly(); String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "(" + offset + "l,o," + length + "," + trim + "," + ascii + "); }"; //add setter CtMethod wmethod = CtNewMethod.make(wmeth, cc); cc.addMethod(wmethod); System.out.println(wmeth); String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadstr" + rcons + "(" + offset + "l," + ascii + "); }"; //add setter CtMethod rmethod = CtNewMethod.make(rmeth, cc); //rmethod.getMethodInfo().addAttribute(attr); cc.addMethod(rmethod); System.out.println(rmeth); int bytesperchar = ascii ? 1 : 2; //pad to 16 bits int ll = 4 + length * bytesperchar; if (ll % 2 != 0) { ll++; } offset += ll; //lebgth marker as well as unicode 16 encoded characters } else if (pds[i].getPropertyType() == CharSequence.class && isInlineString(pds[i])) { //NOTE - only for inline strings - normal strings are handled as extrefs like any other object System.out.println("ITS An inline charsequence!!!!"); int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length(); boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class) .trimOverflow(); boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly(); String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "(" + offset + "l,o," + length + "," + trim + "," + ascii + "); }"; //add setter CtMethod wmethod = CtNewMethod.make(wmeth, cc); cc.addMethod(wmethod); System.out.println(wmeth); String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadcs" + rcons + "(" + offset + "l," + ascii + "); }"; //add setter CtMethod rmethod = CtNewMethod.make(rmeth, cc); //rmethod.getMethodInfo().addAttribute(attr); cc.addMethod(rmethod); System.out.println(rmeth); int bytesperchar = ascii ? 1 : 2; //pad to 8 byte boundary! int ll = (int) Math.ceil((4.0 + length * bytesperchar) / 8) * 8; offset += ll; //lebgth marker as well as unicode 16 encoded characters } else if ((pds[i].getPropertyType() == OHRLongArray.class || pds[i].getPropertyType() == OHRIntArray.class || pds[i].getPropertyType() == OHRShortArray.class || pds[i].getPropertyType() == OHRByteArray.class || pds[i].getPropertyType() == OHRFloatArray.class || pds[i].getPropertyType() == OHRDoubleArray.class || pds[i].getPropertyType() == OHRBooleanArray.class) && pds[i].getReadMethod().isAnnotationPresent(InlineArrayReify.class)) { int bitsperitem = 0; String cldef = null; Class at = pds[i].getPropertyType(); boolean unchecked = pds[i].getReadMethod().isAnnotationPresent(UncheckedBoundsXXX.class); if (at == OHRLongArray.class) { bitsperitem = 8 * 8; cldef = LongInlineOHRArray.class.getName(); } else if (at == OHRIntArray.class) { bitsperitem = 4 * 8; //cldef=IntInlineOHRArrayCop.class.getName(); if (unchecked) { cldef = IntInlineOHRArrayUnchecked.class.getName(); } else { cldef = IntInlineOHRArray.class.getName(); } } if (at == OHRDoubleArray.class) { bitsperitem = 8 * 8; cldef = DoubleInlineOHRArray.class.getName(); } if (at == OHRFloatArray.class) { bitsperitem = 4 * 8; cldef = FloatInlineOHRArray.class.getName(); } if (at == OHRShortArray.class) { bitsperitem = 2 * 8; cldef = ShortInlineOHRArray.class.getName(); } if (at == OHRByteArray.class) { bitsperitem = 1 * 8; cldef = ByteInlineOHRArray.class.getName(); } if (at == OHRBooleanArray.class) { bitsperitem = 1; cldef = BooleanInlineOHRArray.class.getName(); } //NOTE - only for inline strings - normal strings are handled as extrefs like any other object System.out.println("ITS An inline array!!!!"); int length = pds[i].getReadMethod().getAnnotation(InlineArrayReify.class).length(); long bytealloc = OHRInlineArrayHandler.getGenericArrayAllocationSize(bitsperitem, length); //PL.pl("byte allocation for logn array length "+length+" "+bytealloc); CtClass ctc = getDefault().getCtClass(cldef); String varname = "var" + i; CtField cf = new CtField(ctc, varname, cc); cf.setModifiers(Modifier.PRIVATE); cc.addField(cf); //add data to constructor initBuilder.append( "com.industrieit.ohr.OHRInlineArrayHandler.initialiseInlineGenericArray(this.basePtr+" + offset + "l," + length + "l," + bitsperitem + ");\n"); constructBuilder.append(varname + "=new " + cldef + "(this," + offset + "l);\n"); //+ "//this.basePtr"+offset+"l);"); //String wmeth = "public void " + wname + "(" + typ + " o) { throw new java.lang.RuntimeException(\"not supported\"); }"; //add setter //CtMethod wmethod = CtNewMethod.make(wmeth, cc); //cc.addMethod(wmethod); //System.out.println(wmeth); String rmeth = "public " + typ + " " + rname + "() { return " + varname + "; }"; //add setter CtMethod rmethod = CtNewMethod.make(rmeth, cc); //rmethod.getMethodInfo().addAttribute(attr); cc.addMethod(rmethod); System.out.println("||||||||" + rmeth + "|||||||||"); offset += bytealloc; } else if (pds[i].getPropertyType().isPrimitive()) { //PL.pl("ITS A PRIMITIVE!"); int vv = 0; if (cprop == long.class) { vv = 8; } if (cprop == double.class) { vv = 8; } if (cprop == int.class) { vv = 4; } if (cprop == float.class) { vv = 4; } if (cprop == short.class) { vv = 2; } if (cprop == byte.class) { vv = 1; } System.out.println( "for " + pds[i].getName() + " typ is " + pds[i].getPropertyType().getName()); String wmeth = "public void " + wname + "(" + typ + " o) { ohwrite" + wcons + "(" + offset + "l,o); }"; //add setter //ConstPool constpool = cc.getClassFile().getConstPool(); if (reifwrite) { CtMethod wmethod = CtNewMethod.make(wmeth, cc); cc.addMethod(wmethod); System.out.println("&&&&&&&" + wmeth); } String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohread" + typ + rcons + "(" + offset + "l); }"; //add setter //rmethod.getMethodInfo().addAttribute(attr); if (reifread) { CtMethod rmethod = CtNewMethod.make(rmeth, cc); cc.addMethod(rmethod); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&" + rmeth + vv); } offset += vv; } else { System.out.println("ITS AN ASSUMED REIFY!!!"); if (pds[i].getWriteMethod().isAnnotationPresent(Owned.class)) { owned.add(i); } //CtClass tc = getDefault().getCtClass(pds[i].getPropertyType().getName()); CtClass tc = getDefault().getCtClass(OHRBase.class.getName()); //String fnam="ohrt"+i; //CtField f = new CtField(tc, fnam, cc); //f.setModifiers(Modifier.PROTECTED); //cc.addField(f); //store by reify //handleOffsets.add(offset); String wmeth = "public void " + wname + "(" + typ + " o) { ohwritere" + wcons + "(" + offset + "l,o); }"; //add setter CtMethod wmethod = CtNewMethod.make(wmeth, cc); if (reifwrite) { cc.addMethod(wmethod); } System.out.println(wmeth); //String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre(" + offset + "l," + typ + ".class); }"; String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre" + rcons + "(" + offset + "l); };"; //add setter CtMethod rmethod = CtNewMethod.make(rmeth, cc); //rmethod.getMethodInfo().addAttribute(attr); if (reifread) { cc.addMethod(rmethod); } System.out.println(rmeth); handleOffsets.add(offset); offset += 8; } /* if (!isReif(type)) { PL.pl(""+pds[i].getName()+" is a non reified handle!!!!"); //store by handle handleOffsets.add(offset); String wmeth = "public void " + wname + "(" + typ + " o) { ohwritehand(" + offset + "l,o); }"; //add setter CtMethod wmethod = CtNewMethod.make(wmeth, cc); if (reifwrite) { cc.addMethod(wmethod); } System.out.println(wmeth); String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadhand(" + offset + "l); }"; //add setter CtMethod rmethod = CtNewMethod.make(rmeth, cc); //rmethod.getMethodInfo().addAttribute(attr); if (reifread) { cc.addMethod(rmethod); } System.out.println(rmeth); }*/ } //PL.pl("offset is "+offset); } //offset+=8; //ok create the get handleoffsets method //print out total byts allocated //PL.pl("%%%%%%%%%% TOTAL BYTES = " + offset); StringBuilder sb = new StringBuilder(); sb.append("public long[] handleOffsets() { "); sb.append("long a[] = new long[").append(handleOffsets.size()).append("];"); int c = 0; for (long l : handleOffsets) { sb.append("a[").append(c).append("]=").append(l).append("l;"); c++; } sb.append("return a; }"); System.out.println(sb.toString()); CtMethod om = CtNewMethod.make(sb.toString(), cc); cc.addMethod(om); String sizem = "public long gsize() { return " + (offset) + "l; }"; //PL.pl(sizem); CtMethod sm = CtNewMethod.make(sizem, cc); cc.addMethod(sm); //add clsid CtMethod cmid = CtNewMethod.make("public int ohclassId() { return " + clnumber + "; }", cc); cc.addMethod(cmid); setBaseMixinsPost(cc, false, owned, pds, constructBuilder, initBuilder); cc.writeFile("target/classes"); /*for (Method me : cc.toClass().getDeclaredMethods()) { //test print, ok //System.out.println(me.getName()); }*/ Class ppp = Class.forName(cnam); Field f = ppp.getDeclaredField("u"); f.setAccessible(true); f.set(ppp.newInstance(), USafe.getUnsafe()); //synchronized (mutex) //{ processed2.put(cl, ppp); processed2.put(ppp, ppp); cls[clnumber] = ppp; return ppp; //} } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.kamhon.ieagle.util.MessageFactory.java
private void processIsAlwaysReload() { if (isAlwaysReload()) { // remove all object MESSAGE_RESOURCES.clear();//from w w w . j a v a 2 s .c o m Class<?> type = ResourceBundle.class; try { Field cacheList = type.getDeclaredField("cacheList"); cacheList.setAccessible(true); Map<?, ?> cache = (Map<?, ?>) cacheList.get(ResourceBundle.class); cache.clear(); log.debug("cache.size() = " + cache.size()); } catch (Exception ex) { log.fatal(ex, ex.fillInStackTrace()); } } }
From source file:elaborate.tag_analysis.oosm.impl.gson.BaseInterfaceDeserializer.java
private Field getField(Class clz, String fieldName) { Field field = null;/*from w w w .j a v a 2 s . c o m*/ try { field = clz.getDeclaredField(fieldName); } catch (Exception ex) { } if (field == null && clz.getSuperclass() != null) { return this.getField(clz.getSuperclass(), fieldName); } return field; }
From source file:com.db2eshop.governance.UIBinder.java
private Field getField(Class<?> clazz, String fieldName) { try {//from ww w .j a v a 2 s .c o m return clazz.getDeclaredField(fieldName); } catch (Exception e) { return null; } }
From source file:info.raack.appliancelabeler.datacollector.StepgreenTED5000ConfigurationLoaderTest.java
@Before public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, JAXBException, SAXException { dataService = mock(DataService.class); database = mock(Database.class); oauthRequestProcessor = mock(OAuthRequestProcessor.class); emailSender = mock(EmailSender.class); loader = new StepgreenTED5000ConfigurationLoader(); Class<?> c = loader.getClass(); Field f = c.getDeclaredField("dataService"); f.setAccessible(true);/*from w w w. j av a2 s.co m*/ f.set(loader, dataService); f = c.getDeclaredField("oAuthRequestProcessor"); f.setAccessible(true); f.set(loader, oauthRequestProcessor); f = c.getDeclaredField("emailSender"); f.setAccessible(true); f.set(loader, emailSender); f = c.getDeclaredField("energylabelerUrl"); f.setAccessible(true); f.set(loader, "http://www.energylabelerurl.com"); f = c.getDeclaredField("database"); f.setAccessible(true); f.set(loader, database); }