/** * Goes through the class hierarchy and find the authorization annotations attached to a certain * method. * * @param clazz class to be scanned * @param authorizationActionMap the map to be populated */ private void findAuthorizationActions( Class<?> clazz, Map<String, String> authorizationActionMap) { if (clazz == null || clazz == Object.class) { return; } String classAuthorizationActionsAllowed = getAuthorizationActions(clazz.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); for (Method m : clazz.getMethods()) { if (SKIP_METHODS.contains(m.getName())) { continue; } String methodAuthorizationActionsAllowed = getAuthorizationActions(m.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); String authorizationActions = methodAuthorizationActionsAllowed != null ? methodAuthorizationActionsAllowed : classAuthorizationActionsAllowed; if (authorizationActions != null) { authorizationActionMap.put(m.getName(), authorizationActions); } } if (!authorizationActionMap.isEmpty()) { return; } findAuthorizationActions(clazz.getSuperclass(), authorizationActionMap); if (!authorizationActionMap.isEmpty()) { return; } for (Class<?> interfaceCls : clazz.getInterfaces()) { findAuthorizationActions(interfaceCls, authorizationActionMap); } }
private Map<String, SpringResource> generateResourceMap(Set<Class<?>> validClasses) throws GenerateException { Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>(); for (Class<?> c : validClasses) { RequestMapping requestMapping = c.getAnnotation(RequestMapping.class); String description = ""; // This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError // This occurs when a class or method loaded by reflections contains a type that has no // dependency try { resourceMap = analyzeController(c, resourceMap, description); List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods())); if (c.getSuperclass() != null) { mList.addAll(Arrays.asList(c.getSuperclass().getMethods())); } } catch (NoClassDefFoundError e) { LOG.error(e.getMessage()); LOG.info(c.getName()); // exception occurs when a method type or annotation is not recognized by the plugin } catch (ClassNotFoundException e) { LOG.error(e.getMessage()); LOG.info(c.getName()); } } return resourceMap; }
private static Optional<Method> lookup( Class<?> sourceClass, String methodName, Class<?>[] parameterTypes) { Method match; try { match = sourceClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return Optional.absent(); } LinkedList<Class<?>> queue = new LinkedList<Class<?>>(); queue.add(sourceClass); while (!queue.isEmpty()) { Class<?> c = queue.removeFirst(); try { match = c.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { // ignore } for (Class<?> interfaceType : c.getInterfaces()) { queue.addFirst(interfaceType); } if (c.getSuperclass() != null) { queue.addFirst(c.getSuperclass()); } } match.setAccessible(true); return Optional.of(match); }
public SqlRexConvertlet get(SqlCall call) { SqlRexConvertlet convertlet; final SqlOperator op = call.getOperator(); // Is there a convertlet for this operator // (e.g. SqlStdOperatorTable.plusOperator)? convertlet = (SqlRexConvertlet) map.get(op); if (convertlet != null) { return convertlet; } // Is there a convertlet for this class of operator // (e.g. SqlBinaryOperator)? Class<? extends Object> clazz = op.getClass(); while (clazz != null) { convertlet = (SqlRexConvertlet) map.get(clazz); if (convertlet != null) { return convertlet; } clazz = clazz.getSuperclass(); } // Is there a convertlet for this class of expression // (e.g. SqlCall)? clazz = call.getClass(); while (clazz != null) { convertlet = (SqlRexConvertlet) map.get(clazz); if (convertlet != null) { return convertlet; } clazz = clazz.getSuperclass(); } return null; }
private void addClass(Class<?> c) { if (classes.add(c)) { if (c.getSuperclass() != null) { addClass(c.getSuperclass()); } for (Class<?> sc : c.getInterfaces()) { addClass(sc); } for (Class<?> dc : c.getDeclaredClasses()) { addClass(dc); } for (Method m : c.getDeclaredMethods()) { addClass(m.getReturnType()); for (Class<?> p : m.getParameterTypes()) { addClass(p); } } if (c != void.class && dimensions(c) < 2) { Class<?> arrayClass = Array.newInstance(c, 0).getClass(); arrayClasses.put(c, arrayClass); addClass(arrayClass); } } }
/** * Helper method that can be used to dynamically figure out formal enumeration type (class) for * given class of an enumeration value. This is either class of enum instance (for "simple" * enumerations), or its superclass (for enums with instance fields or methods) */ @SuppressWarnings("unchecked") public static Class<? extends Enum<?>> findEnumType(Class<?> cls) { // enums with "body" are sub-classes of the formal type if (cls.getSuperclass() != Enum.class) { cls = cls.getSuperclass(); } return (Class<? extends Enum<?>>) cls; }
/** * Create MBean for Object. Attempts to create an MBean for the object by searching the package * and class name space. For example an object of the type * * <PRE> * class com.acme.MyClass extends com.acme.util.BaseClass * </PRE> * * Then this method would look for the following classes: * * <UL> * <LI>com.acme.MyClassMBean * <LI>com.acme.jmx.MyClassMBean * <LI>com.acme.util.BaseClassMBean * <LI>com.acme.util.jmx.BaseClassMBean * </UL> * * @param o The object * @return A new instance of an MBean for the object or null. */ public static ModelMBean mbeanFor(Object o) { try { Class oClass = o.getClass(); ClassLoader loader = oClass.getClassLoader(); ModelMBean mbean = null; boolean jmx = false; Class[] interfaces = null; int i = 0; while (mbean == null && oClass != null) { Class focus = interfaces == null ? oClass : interfaces[i]; String pName = focus.getPackage().getName(); String cName = focus.getName().substring(pName.length() + 1); String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean"; try { Class mClass = loader.loadClass(mName); if (log.isTraceEnabled()) log.trace("mbeanFor " + o + " mClass=" + mClass); mbean = (ModelMBean) mClass.newInstance(); mbean.setManagedResource(o, "objectReference"); if (log.isDebugEnabled()) log.debug("mbeanFor " + o + " is " + mbean); return mbean; } catch (ClassNotFoundException e) { if (e.toString().endsWith("MBean")) { if (log.isTraceEnabled()) log.trace(e.toString()); } else log.warn(LogSupport.EXCEPTION, e); } catch (Error e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } if (jmx) { if (interfaces != null) { i++; if (i >= interfaces.length) { interfaces = null; oClass = oClass.getSuperclass(); } } else { interfaces = oClass.getInterfaces(); i = 0; if (interfaces == null || interfaces.length == 0) { interfaces = null; oClass = oClass.getSuperclass(); } } } jmx = !jmx; } } catch (Exception e) { LogSupport.ignore(log, e); } return null; }
public Field getDeclaredField(Class clazz, String fieldName) throws Exception { Field field = clazz.getDeclaredField(fieldName); if (field == null && clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) { return getDeclaredField(clazz.getSuperclass(), fieldName); } return field; }
/** * Helper method that can be used to dynamically figure out formal enumeration type (class) for * given enumeration. This is either class of enum instance (for "simple" enumerations), or its * superclass (for enums with instance fields or methods) */ @SuppressWarnings("unchecked") public static Class<? extends Enum<?>> findEnumType(Enum<?> en) { // enums with "body" are sub-classes of the formal type Class<?> ec = en.getClass(); if (ec.getSuperclass() != Enum.class) { ec = ec.getSuperclass(); } return (Class<? extends Enum<?>>) ec; }
private Object[] fillResultWithAllParamProviderMethods(Class<?> sourceClass) { ArrayList<Object> result = new ArrayList<Object>(); while (sourceClass.getSuperclass() != null) { result.addAll(gatherParamsFromAllMethodsFrom(sourceClass)); sourceClass = sourceClass.getSuperclass(); } if (result.isEmpty()) throw new RuntimeException( "No methods starting with provide or they return no result in the parameters source class: " + sourceClass.getName()); return result.toArray(new Object[] {}); }
public static Collection<Class> getAllInterfaces( final Class aClass, final Collection<Class> result) { final Class[] interfaces = aClass.getInterfaces(); ContainerUtil.addAll(result, interfaces); if (aClass.getSuperclass() != null) { getAllInterfaces(aClass.getSuperclass(), result); } for (Class anInterface : interfaces) { getAllInterfaces(anInterface, result); } return result; }
/** * Prints information about a class' parents and methods to a PrintWriter * * @param object * @param printer */ public static void printClassInfo(Object object, PrintWriter printer) { if (object == null) { printer.println("null"); return; } Class<?> type = object.getClass(); printer.println(type); if (type.getSuperclass() != null) printer.println("extends " + type.getSuperclass()); for (Class<?> interf : type.getInterfaces()) printer.println("implements " + interf); for (Method method : type.getMethods()) { printer.println(method); } }
static Method[] getOverridableMethods(Class<?> clazz) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); // Check superclasses before interfaces so we always choose // implemented methods over abstract ones, even if a subclass // re-implements an interface already implemented in a superclass // (e.g. java.util.ArrayList) for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { appendOverridableMethods(c, list, skip); } for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { for (Class<?> intf : c.getInterfaces()) appendOverridableMethods(intf, list, skip); } return list.toArray(new Method[list.size()]); }
private static Field getFieldFromBean( Class<?> clazz, String fieldName, final Class<?> originalClass) { try { 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); } }
public List<Model.Property> listProperties() { List<Model.Property> properties = new ArrayList<Model.Property>(); Set<Field> fields = new LinkedHashSet<Field>(); Class<?> tclazz = clazz; while (!tclazz.equals(Object.class)) { Collections.addAll(fields, tclazz.getDeclaredFields()); tclazz = tclazz.getSuperclass(); } for (Field f : fields) { int mod = f.getModifiers(); if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) { continue; } if (f.isAnnotationPresent(Transient.class)) { continue; } if (f.isAnnotationPresent(NoBinding.class)) { NoBinding a = f.getAnnotation(NoBinding.class); List<String> values = Arrays.asList(a.value()); if (values.contains("*")) { continue; } } Model.Property mp = buildProperty(f); if (mp != null) { properties.add(mp); } } return properties; }
public static void main(String[] args) { // read class name from command line args or user input String name; if (args.length > 0) name = args[0]; else { Scanner in = new Scanner(System.in); System.out.println("Enter class name (e.g. java.util.Date): "); name = in.next(); } try { // print class name and superclass name (if != Object) Class cl = Class.forName(name); Class supercl = cl.getSuperclass(); String modifiers = Modifier.toString(cl.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print("class " + name); if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName()); System.out.print("\n{\n"); printConstructors(cl); System.out.println(); printMethods(cl); System.out.println(); printFields(cl); System.out.println("}"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); }
static Method[] getOverridableMethods(Class c) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } c = c.getSuperclass(); } return list.toArray(new Method[list.size()]); }
/** * Goes through the class hierarchy and figure out the supertenant annotations coupled with * operations/methods. * * @param clazz * @param superTenantServiceSet */ private void findSuperTenantServices(Class<?> clazz, Set<String> superTenantServiceSet) { if (clazz == null || clazz == Object.class) { return; } for (Method m : clazz.getMethods()) { if (SKIP_METHODS.contains(m.getName())) { continue; } boolean isSuperTenantService = getSuperTenantServices(m.getAnnotations(), TENANT_ANNOTATION_CLASS_NAME); if (isSuperTenantService) { superTenantServiceSet.add(m.getName()); } } if (!superTenantServiceSet.isEmpty()) { return; } findSuperTenantServices(clazz.getSuperclass(), superTenantServiceSet); if (!superTenantServiceSet.isEmpty()) { return; } for (Class<?> interfaceCls : clazz.getInterfaces()) { findSuperTenantServices(interfaceCls, superTenantServiceSet); } }
public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) { List<Class<?>> jarClasses = new ArrayList<Class<?>>(); for (String className : dag.getClassNames()) { try { Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className); jarClasses.add(clazz); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Failed to load class " + className, e); } } for (Class<?> clazz : Lists.newArrayList(jarClasses)) { // process class and super classes (super does not require deploy annotation) for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) { // LOG.debug("checking " + c); jarClasses.add(c); jarClasses.addAll(Arrays.asList(c.getInterfaces())); } } jarClasses.addAll(Arrays.asList(defaultClasses)); if (dag.isDebug()) { LOG.debug("Deploy dependencies: {}", jarClasses); } LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates HashMap<String, String> sourceToJar = new HashMap<String, String>(); for (Class<?> jarClass : jarClasses) { if (jarClass.getProtectionDomain().getCodeSource() == null) { // system class continue; } String sourceLocation = jarClass.getProtectionDomain().getCodeSource().getLocation().toString(); String jar = sourceToJar.get(sourceLocation); if (jar == null) { // don't create jar file from folders multiple times jar = JarFinder.getJar(jarClass); sourceToJar.put(sourceLocation, jar); LOG.debug("added sourceLocation {} as {}", sourceLocation, jar); } if (jar == null) { throw new AssertionError("Cannot resolve jar file for " + jarClass); } localJarFiles.add(jar); } String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS); if (!StringUtils.isEmpty(libJarsPath)) { String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP); localJarFiles.addAll(Arrays.asList(libJars)); } LOG.info("Local jar file dependencies: " + localJarFiles); return localJarFiles; }
public static <C, I> Type[] getGenericInterfaceParams( Class<C> checkedClass, Class<I> searchedInterface) { for (Type type : checkedClass.getGenericInterfaces()) { ParameterizedType pt = (ParameterizedType) type; if (searchedInterface.equals(pt.getRawType())) { ParameterizedType pType = ((ParameterizedType) type); return pType.getActualTypeArguments(); } } if (!Object.class.equals(checkedClass.getSuperclass())) return getGenericInterfaceParams(checkedClass.getSuperclass(), searchedInterface); throw new ConfigurationError( checkedClass + " does not implement interface with generic parameters: " + searchedInterface); }
private ITemplate templateInstance_() { if (!isValid) return NULL_TEMPLATE; if (null == templateInstance) { try { if (Logger.isTraceEnabled()) logger.trace("About to new template instance"); Class<?> clz = getJavaClass(); if (Logger.isTraceEnabled()) logger.trace("template java class loaded"); templateInstance = (TemplateBase) clz.newInstance(); if (Logger.isTraceEnabled()) logger.trace("template instance generated"); } catch (RythmException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error load template instance for " + getKey(), e); } } if (!engine().isProdMode()) { // check parent class change Class<?> c = templateInstance.getClass(); Class<?> pc = c.getSuperclass(); if (null != pc && !Modifier.isAbstract(pc.getModifiers())) { engine().classes.getByClassName(pc.getName()); } } templateInstance.setTemplateClass(this); return templateInstance; }
/** * Verifies if the element is an instance of a class with a given class name. If direct match * fails, implementing interfaces will be tested, then recursively all superclasses and their * interfaces. */ private boolean verifyClass(Object element, String className) { Class eclass = element.getClass(); Class clazz = eclass; boolean match = false; while (clazz != null) { // test the class itself if (clazz.getName().equals(className)) { match = true; break; } // test all the interfaces it implements Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].getName().equals(className)) { match = true; break; } } if (match == true) { break; } // get the superclass clazz = clazz.getSuperclass(); } return match; }
protected void _addFields(Map<String, AnnotatedField> fields, Class<?> c) { /* First, a quick test: we only care for regular classes (not * interfaces, primitive types etc), except for Object.class. * A simple check to rule out other cases is to see if there * is a super class or not. */ Class<?> parent = c.getSuperclass(); if (parent != null) { // Let's add super-class' fields first, then ours. /* 21-Feb-2010, tatu: Need to handle masking: as per [JACKSON-226] * we otherwise get into trouble... */ _addFields(fields, parent); for (Field f : c.getDeclaredFields()) { // static fields not included, nor transient if (!_isIncludableField(f)) { continue; } /* Ok now: we can (and need) not filter out ignorable fields * at this point; partly because mix-ins haven't been * added, and partly because logic can be done when * determining get/settability of the field. */ fields.put(f.getName(), _constructField(f)); } // And then... any mix-in overrides? if (_mixInResolver != null) { Class<?> mixin = _mixInResolver.findMixInClassFor(c); if (mixin != null) { _addFieldMixIns(mixin, fields); } } } }
/** * Tries to locate named library from the current ClassLoader This method exists because native * libraries are loaded from native code, and as such is exempt from ClassLoader library loading * rutines. It therefore always fails. We therefore invoke the protected method of the ClassLoader * to see if it can locate it. * * @param libname Name of library to search for * @param classloader Classloader to use * @return Absolute path to library if found, otherwise null */ private static String getPathFromClassLoader( final String libname, final ClassLoader classloader) { try { log("getPathFromClassLoader: searching for: " + libname); Class<?> c = classloader.getClass(); while (c != null) { final Class<?> clazz = c; try { return AccessController.doPrivileged( new PrivilegedExceptionAction<String>() { public String run() throws Exception { Method findLibrary = clazz.getDeclaredMethod("findLibrary", String.class); findLibrary.setAccessible(true); String path = (String) findLibrary.invoke(classloader, libname); return path; } }); } catch (PrivilegedActionException e) { log("Failed to locate findLibrary method: " + e.getCause()); c = c.getSuperclass(); } } } catch (Exception e) { log("Failure locating " + e + " using classloader:" + e); } return null; }
/** * Assumes that all of the parents of c have been registered already. * * @param c */ @SuppressWarnings("unchecked") private <T> Node registerClass(final Class<T> c) throws ClassHierarchyException { if (c.isArray()) { throw new UnsupportedOperationException("Can't register array types"); } try { return getAlreadyBoundNode(c); } catch (final NameResolutionException e) { // node not bound yet } final Node n = buildPathToNode(c); if (n instanceof ClassNode) { final ClassNode<T> cn = (ClassNode<T>) n; final Class<T> superclass = (Class<T>) c.getSuperclass(); if (superclass != null) { try { ((ClassNode<T>) getAlreadyBoundNode(superclass)).putImpl(cn); } catch (final NameResolutionException e) { throw new IllegalStateException(e); } } for (final Class<?> interf : c.getInterfaces()) { try { ((ClassNode<T>) getAlreadyBoundNode(interf)).putImpl(cn); } catch (final NameResolutionException e) { throw new IllegalStateException(e); } } } return n; }
private Class<? extends GAttrib> attrclass(Class<? extends GAttrib> cl) { while (true) { Class<?> p = cl.getSuperclass(); if (p == GAttrib.class) return (cl); cl = p.asSubclass(GAttrib.class); } }
// // Find all the java.sql interfaces implemented by a class and find // the methods in those interfaces which raise // SQLFeatureNotSupportedException when called on the passed-in candidate object. // private void vetInterfaces( Object candidate, Class myClass, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { Class superClass = myClass.getSuperclass(); if (superClass != null) { vetInterfaces(candidate, superClass, unsupportedList, notUnderstoodList); } // // The contract for Class.getInterfaces() states that the interfaces // come back in a deterministic order, namely, in the order that // they were declared in the "extends" clause. // Class<?>[] interfaces = myClass.getInterfaces(); int interfaceCount = interfaces.length; for (int i = 0; i < interfaceCount; i++) { Class<?> iface = interfaces[i]; if (iface.getPackage().getName().equals(SQL_PACKAGE_NAME)) { vetInterfaceMethods(candidate, iface, unsupportedList, notUnderstoodList); } vetInterfaces(candidate, iface, unsupportedList, notUnderstoodList); } }
Field[] keyFields() { Class c = clazz; try { List<Field> fields = new ArrayList<Field>(); while (!c.equals(Object.class)) { for (Field field : c.getDeclaredFields()) { // TODO: add cashe field->isAnnotationPresent if (InternalCache.isEnableAnnotationPresent()) { if (InternalCache.isAnnotationPresent(Id.class, field) || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) { field.setAccessible(true); fields.add(field); } } else { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) { field.setAccessible(true); fields.add(field); } } } c = c.getSuperclass(); } final Field[] f = fields.toArray(new Field[fields.size()]); if (f.length == 0) { throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz); } return f; } catch (Exception e) { throw new UnexpectedException( "Error while determining the object @Id for an object of type " + clazz); } }
public static void clearFields(final Object test) throws IllegalAccessException { Class aClass = test.getClass(); while (aClass != null) { clearDeclaredFields(test, aClass); aClass = aClass.getSuperclass(); } }
private Field[] getAccessibleFields() { if (includePrivate) { try { List<Field> fieldsList = new ArrayList<Field>(); Class<?> currentClass = cl; while (currentClass != null) { // get all declared fields in this class, make them // accessible, and save Field[] declared = currentClass.getDeclaredFields(); for (int i = 0; i < declared.length; i++) { declared[i].setAccessible(true); fieldsList.add(declared[i]); } // walk up superclass chain. no need to deal specially with // interfaces, since they can't have fields currentClass = currentClass.getSuperclass(); } return fieldsList.toArray(new Field[fieldsList.size()]); } catch (SecurityException e) { // fall through to !includePrivate case } } return cl.getFields(); }