List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:com.industrieit.ohr.OHRJavassister.java
public static Class ohr(Class cll) { try {//from w ww . j a v a2 s.co 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:org.syncope.core.rest.controller.TaskController.java
@PreAuthorize("hasRole('TASK_LIST')") @RequestMapping(method = RequestMethod.GET, value = "/jobClasses") public ModelAndView getJobClasses() { CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory(); Set<String> jobClasses = new HashSet<String>(); try {/*from ww w.j a v a2 s. c o m*/ for (Resource resource : resResolver.getResources("classpath*:**/*.class")) { ClassMetadata metadata = cachingMetadataReaderFactory.getMetadataReader(resource) .getClassMetadata(); if (ArrayUtils.contains(metadata.getInterfaceNames(), Job.class.getName()) || AbstractTaskJob.class.getName().equals(metadata.getSuperClassName()) || ArrayUtils.contains(metadata.getInterfaceNames(), StatefulJob.class.getName())) { try { Class jobClass = Class.forName(metadata.getClassName()); if (!Modifier.isAbstract(jobClass.getModifiers()) && !metadata.hasEnclosingClass() && !jobClass.equals(SyncJob.class) && !jobClass.equals(ReportJob.class) && !jobClass.equals(NotificationJob.class)) { jobClasses.add(jobClass.getName()); } } catch (ClassNotFoundException e) { LOG.error("Could not load class {}", metadata.getClassName(), e); } } } } catch (IOException e) { LOG.error("While searching for class implementing {}", Job.class.getName(), e); } ModelAndView result = new ModelAndView(); result.addObject(jobClasses); return result; }
From source file:org.dllearner.core.AnnComponentManager.java
private AnnComponentManager() { if (componentClassNames == null) { componentClassNames = new ArrayList<>(); if (reflectionScanner == null) { org.apache.log4j.Logger.getLogger(Reflections.class).setLevel(Level.OFF); reflectionScanner = new Reflections("org.dllearner"); }//from w w w. j a va 2 s. co m Set<Class<? extends Component>> componentClasses = reflectionScanner.getSubTypesOf(Component.class); Set<Class<?>> componentAnnClasses = reflectionScanner.getTypesAnnotatedWith(ComponentAnn.class, true); for (Class<?> clazz : Sets.intersection(componentClasses, componentAnnClasses)) { if (!Modifier.isAbstract(clazz.getModifiers())) componentClassNames.add(clazz.getCanonicalName()); } for (Class<?> clazz : Sets.difference(componentClasses, componentAnnClasses)) { if (!Modifier.isAbstract(clazz.getModifiers())) logger.debug("Warning: " + clazz.getCanonicalName() + " implements Component but is not annotated, ignored"); } } // conversion of class strings to objects components = new TreeSet<>((Comparator<Class<? extends Component>>) (o1, o2) -> { return o1.getName().compareTo(o2.getName()); }); componentNames = new DualHashBidiMap<>(); componentNamesShort = new DualHashBidiMap<>(); for (String componentClassName : componentClassNames) { try { Class<? extends Component> component = Class.forName(componentClassName) .asSubclass(Component.class); components.add(component); componentNames.put(component, getName(component)); componentNamesShort.put(component, getShortName(component)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java
/** * Learn whether this BasicTypeConverter can create a collection of the specified type. * @param type prospective destination class * @return boolean/*from w w w .java 2 s. c om*/ */ protected boolean canCreateCollection(Class type) { if (!type.isInterface() && ((type.getModifiers() & Modifier.ABSTRACT) == 0)) { try { type.getConstructor(new Class[0]); return true; } catch (Exception e) { return false; } } return type == List.class || type == Collection.class || type == Set.class; }
From source file:org.apache.struts2.config.ClasspathConfigurationProvider.java
/** * Scan a list of packages for Action classes. * * This method loads classes that implement the Action interface * or have a class name that ends with the letters "Action". * * @param pkgs A list of packages to load * @see #processActionClass// w w w.j av a 2s . com */ protected void loadPackages(String[] pkgs) { ResolverUtil<Class> resolver = new ResolverUtil<Class>(); resolver.find(new Test() { // Match Action implementations and classes ending with "Action" public boolean matches(Class type) { // TODO: should also find annotated classes return (Action.class.isAssignableFrom(type) || type.getSimpleName().endsWith("Action")); } }, pkgs); Set<? extends Class<? extends Class>> actionClasses = resolver.getClasses(); for (Object obj : actionClasses) { Class cls = (Class) obj; if (!Modifier.isAbstract(cls.getModifiers())) { processActionClass(cls, pkgs); } } for (String key : loadedPackageConfigs.keySet()) { configuration.addPackageConfig(key, loadedPackageConfigs.get(key)); } }
From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java
/** * Create a collection of a given type.//from ww w . ja va 2 s . co m * @param type destination class * @return Collection */ protected Collection allocateCollection(Class type) { if (!type.isInterface() && ((type.getModifiers() & Modifier.ABSTRACT) == 0)) { try { return (Collection) type.newInstance(); } catch (Exception ex) { throw new JXPathInvalidAccessException("Cannot create collection of type: " + type, ex); } } if (type == List.class || type == Collection.class) { return new ArrayList(); } if (type == Set.class) { return new HashSet(); } throw new JXPathInvalidAccessException("Cannot create collection of type: " + type); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
/** * Throw appropriate exception if the given type is final. *///from ww w .j av a 2 s. c o m private static void assertNotFinal(Class type) { if (Modifier.isFinal(type.getModifiers())) throw new UnsupportedException(_loc.get("no-proxy-final", type)); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
private static boolean isProxyable(Class<?> cls) { int mod = cls.getModifiers(); if (Modifier.isFinal(mod)) return false; if (Modifier.isProtected(mod) || Modifier.isPublic(mod)) return true; // Default scoped class, we can only extend if it is in the same package as the generated proxy. Ideally // we'd fix the code gen portion and place proxies in the same pacakge as the types being proxied. if (cls.getPackage().getName().equals("org.apache.openjpa.util")) return true; return false; }
From source file:com.baidu.bjf.remoting.protobuf.IDLProxyObject.java
private IDLProxyObject doSetFieldValue(String fullField, String field, Object value, Object object, boolean useCache, Map<String, ReflectInfo> cachedFields) { Field f;/*from ww w. java 2s . c om*/ // check cache if (useCache) { ReflectInfo info = cachedFields.get(fullField); if (info != null) { setField(value, info.target, info.field); return this; } } int index = field.indexOf('.'); if (index != -1) { String parent = field.substring(0, index); String sub = field.substring(index + 1); try { f = FieldUtils.findField(object.getClass(), parent); if (f == null) { throw new RuntimeException( "No field '" + parent + "' found at class " + object.getClass().getName()); } Class<?> type = f.getType(); f.setAccessible(true); Object o = f.get(object); if (o == null) { boolean memberClass = type.isMemberClass(); if (memberClass && Modifier.isStatic(type.getModifiers())) { Constructor<?> constructor = type.getConstructor(new Class[0]); constructor.setAccessible(true); o = constructor.newInstance(new Object[0]); } else if (memberClass) { Constructor<?> constructor = type.getConstructor(new Class[] { object.getClass() }); constructor.setAccessible(true); o = constructor.newInstance(new Object[] { object }); } else { o = type.newInstance(); } f.set(object, o); } return put(fullField, sub, value, o); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } f = FieldUtils.findField(object.getClass(), field); if (f == null) { throw new RuntimeException("No field '" + field + "' found at class " + object.getClass().getName()); } if (useCache && !cachedFields.containsKey(fullField)) { cachedFields.put(fullField, new ReflectInfo(f, object)); } setField(value, object, f); return this; }
From source file:com.datatorrent.stram.client.StramAppLauncher.java
/** * Scan the application jar file entries for configuration classes. * This needs to occur in a class loader with access to the application dependencies. *///from w ww .ja v a2 s . co m private void findAppConfigClasses(List<String> classFileNames) { URLClassLoader cl = URLClassLoader .newInstance(launchDependencies.toArray(new URL[launchDependencies.size()])); for (final String classFileName : classFileNames) { final String className = classFileName.replace('/', '.').substring(0, classFileName.length() - 6); try { final Class<?> clazz = cl.loadClass(className); if (!Modifier.isAbstract(clazz.getModifiers()) && StreamingApplication.class.isAssignableFrom(clazz)) { final AppFactory appConfig = new AppFactory() { @Override public String getName() { return classFileName; } @Override public String getDisplayName() { ApplicationAnnotation an = clazz.getAnnotation(ApplicationAnnotation.class); if (an != null) { return an.name(); } else { return classFileName; } } @Override public LogicalPlan createApp(LogicalPlanConfiguration conf) { // load class from current context class loader Class<? extends StreamingApplication> c = StramUtils.classForName(className, StreamingApplication.class); StreamingApplication app = StramUtils.newInstance(c); LogicalPlan dag = new LogicalPlan(); conf.prepareDAG(dag, app, getName()); return dag; } }; appResourceList.add(appConfig); } } catch (Throwable e) { // java.lang.NoClassDefFoundError LOG.error("Unable to load class: " + className + " " + e); } } }