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); } } }
/** Return the class with the given name. */ private static Class getClassImpl(Class parent, String name) throws ClassNotFoundException { Class[] clazzes = parent.getDeclaredClasses(); for (int i = 0; i < clazzes.length; i++) { if (clazzes[i].getName().equals(parent.getName() + "$" + name)) return clazzes[i]; } throw new ClassNotFoundException("Invalid class : " + parent.getName() + "$" + name); }
private static void registerSubTileWithMini(String key, Class<? extends SubTileEntity> clazz) { BotaniaAPI.registerSubTile(key, clazz); for (Class innerClazz : clazz.getDeclaredClasses()) if (innerClazz.getSimpleName().equals("Mini")) BotaniaAPI.registerMiniSubTile(key + "Chibi", innerClazz, key); }
private void verifyExternalClass(final Class clazz) { // don't recommended to instantiate the class doing clazz.newInstance(). clazz.getDeclaredConstructors(); clazz.getDeclaredFields(); clazz.getDeclaredMethods(); clazz.getDeclaredClasses(); clazz.getDeclaredAnnotations(); }
public static Class<?> getDeclaredClass(String className, Class<?> containingClass) { for (Class<?> declaredClass : containingClass.getDeclaredClasses()) { if (declaredClass.getSimpleName().equals(className)) { return declaredClass; } } return null; }
/** * Returns inner class with the specified name. * * @param fromClass class to look for the inner class * @param innerClassName inner class name * @return inner class with the specified name */ public static Class getInnerClass(final Class fromClass, final String innerClassName) { for (final Class innerClass : fromClass.getDeclaredClasses()) { if (getClassName(innerClass).equals(innerClassName)) { return innerClass; } } return null; }
/** * Searches the class for the specified inner class. * * @param clz the class to search in. * @param simpleName the simpleName of the class to find * @returns the class being searched for, or null if it can't be found. */ private Class<?> findInnerClassByName(Class<?> clz, String simpleName) { for (Class<?> c : clz.getDeclaredClasses()) { if (c.getSimpleName().equals(simpleName)) { return c; } } return null; }
private void analyze(Class<?> cls, boolean topLevel) { if (!Modifier.isPublic(cls.getModifiers())) { return; } Lookup lookup = MethodHandles.lookup(); if (topLevel) { this.constructor = new DynamicConstructor(getCoercionMatrix()); Constructor<?>[] constructors = cls.getConstructors(); for (int i = 0; i < constructors.length; ++i) { try { this.constructor.addConstructorHandle(lookup.unreflectConstructor(constructors[i])); } catch (IllegalAccessException e) { } } } Method[] methods = getTargetClass().getMethods(); for (int i = 0; i < methods.length; ++i) { int modifiers = methods[i].getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) { analyzeMethod(methods[i]); } } Field[] fields = getTargetClass().getFields(); for (int i = 0; i < fields.length; ++i) { int modifiers = fields[i].getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) { analyzeField(fields[i]); } } if (cls.getSuperclass() != null) { analyze(cls.getSuperclass(), false); } Class<?>[] interfaces = cls.getInterfaces(); for (int i = 0; i < interfaces.length; ++i) { analyze(interfaces[i], false); } Class<?>[] innerClasses = cls.getDeclaredClasses(); for (int i = 0; i < innerClasses.length; ++i) { int modifiers = innerClasses[i].getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) { this.propertyReaders.put( innerClasses[i].getSimpleName(), MethodHandles.constant(Class.class, innerClasses[i])); } } }
private static int queryEnums(Class<?> clazz, Hashtable<String, Class<?>> enums) { int enumConstantCount = 0; Class<?> declaredClasses[] = clazz.getDeclaredClasses(); for (Class<?> declaredClass : declaredClasses) enumConstantCount += putEnumTypeInHash(declaredClass, enums); return enumConstantCount; }
public Zadanie2() { String className = JOptionPane.showInputDialog("Podaj nazwę klasy"); Class<?> cls = null; try { cls = Class.forName(className); Class<?>[] classes = cls.getDeclaredClasses(); for (Class<?> c : classes) { System.out.println("Własciwości obiektu " + c.getCanonicalName()); Class<?>[] cl = c.getDeclaredClasses(); for (Class<?> cc : cl) { System.out.println("\t" + cc.getCanonicalName()); } } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Determine imports for the given bundle. Based on the user settings, this method will consider * only the the test hierarchy until the testing framework is found or all classes available * inside the test bundle. * * <p>Note that split packages are not supported. * * @return */ private String[] determineImports() { boolean useTestClassOnly = false; // no jar entry present, bail out. if (jarEntries == null || jarEntries.isEmpty()) { logger.debug("No test jar content detected, generating bundle imports from the test class"); useTestClassOnly = true; } else if (createManifestOnlyFromTestClass()) { logger.info("Using the test class for generating bundle imports"); useTestClassOnly = true; } else logger.info("Using all classes in the jar for the generation of bundle imports"); // className, class resource Map entries; if (useTestClassOnly) { entries = new LinkedHashMap(4); // get current class (test class that bootstraps the OSGi infrastructure) Class<?> clazz = getClass(); String clazzPackage = null; String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName(); do { // consider inner classes as well List classes = new ArrayList(4); classes.add(clazz); CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes); for (Iterator iterator = classes.iterator(); iterator.hasNext(); ) { Class<?> classToInspect = (Class) iterator.next(); Package pkg = classToInspect.getPackage(); if (pkg != null) { clazzPackage = pkg.getName(); String classFile = ClassUtils.getClassFileName(classToInspect); entries.put( classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX), new InputStreamResource(classToInspect.getResourceAsStream(classFile))); } // handle default package else { logger.warn("Could not find package for class " + classToInspect + "; ignoring..."); } } clazz = clazz.getSuperclass(); } while (!endPackage.equals(clazzPackage)); } else entries = jarEntries; return determineImportsFor(entries); }
@Override public IClassDescriptor[] getDeclaredClasses() { Class<?>[] classes = mClass.getDeclaredClasses(); IClassDescriptor[] iclasses = new IClassDescriptor[classes.length]; for (int i = 0; i < classes.length; i++) { iclasses[i] = new ClassWrapper(classes[i]); } return iclasses; }
/** * Retrieves a given inner class definition from the specified outer class. * * @param cls the outer Class * @param innerClassName the fully-qualified name of the inner class of interest */ private static Class getInnerClass(Class cls, String innerClassName) { Class result = null; Class[] innerClasses = cls.getDeclaredClasses(); for (Class c : innerClasses) { if (c.getName().equals(innerClassName)) { result = c; break; } } return result; }
private static void getSelectColumns(final Class<?> klass, final StringBuilder builder) throws Exception { final Field[] fields = klass.getFields(); for (final Field field : fields) { getSelectColumn(field, builder); } final Class<?>[] klasses = klass.getDeclaredClasses(); for (int i = 0; i < klasses.length; i++) { getSelectColumns(klasses[i], builder); } }
public static ItemStack getItemStack(String modid, String name, int stackSize, int metadata) { if (classNames.containsKey(modid)) { // Use classNames for (String classname : classNames.get(modid)) { try { Class klass = null; if (classname.split("\\$").length == 1) { klass = CrossModUtils.class.getClassLoader().loadClass(classname); } else { klass = CrossModUtils.class.getClassLoader().loadClass(classname.split("\\$")[0]); for (Class innerklass : klass.getDeclaredClasses()) { if (innerklass.getName().equals(classname)) klass = innerklass; } } if (klass != null) { Object o = klass.getField(name).get(null); if (o instanceof Block) return new ItemStack((Block) o, stackSize, metadata); else if (o instanceof Item) return new ItemStack((Item) o, stackSize, metadata); else if (o instanceof Integer) return new ItemStack(((Integer) o).intValue(), stackSize, metadata); else { try { int id = klass.getField(name).getInt(null); return new ItemStack(id, stackSize, metadata); } catch (Exception e) { AsieLibMod.log.warning( "Could not get right object for field " + name + " in class " + classNames.get(modid)); } } } } catch (Exception e) { e.printStackTrace(); } } // We're still here!? AsieLibMod.log.severe( "Could not load class for mod " + modid + ", trying worst-case alternatives - PROBABLY BROKEN"); } if (GameRegistry.findBlock(modid, name) != null) return new ItemStack(GameRegistry.findBlock(modid, name), stackSize, metadata); else if (GameRegistry.findItem(modid, name) != null) return new ItemStack(GameRegistry.findItem(modid, name), stackSize, metadata); else if (GameRegistry.findItemStack(modid, name, stackSize) != null) { ItemStack stack = GameRegistry.findItemStack(modid, name, stackSize); if (stack != null) stack.setItemDamage(metadata); return stack; } return null; // in case we already haven't }
private static void findAnnotatedClasses(List<Class<?>> classList, File dir, int level) throws SQLException, IOException { for (File file : dir.listFiles()) { if (file.isDirectory()) { // recurse if we aren't deep enough if (level < maxFindSourceLevel) { findAnnotatedClasses(classList, file, level + 1); } continue; } // skip non .java files if (!file.getName().endsWith(".java")) { continue; } String packageName = getPackageOfClass(file); if (packageName == null) { System.err.println("Could not find package name for: " + file); continue; } // get the filename and cut off the .java String name = file.getName(); name = name.substring(0, name.length() - ".java".length()); String className = packageName + "." + name; Class<?> clazz; try { clazz = Class.forName(className); } catch (Throwable t) { // amazingly, this sometimes throws an Error System.err.println("Could not load class file for: " + file); System.err.println(" " + t); continue; } if (classHasAnnotations(clazz)) { classList.add(clazz); } // handle inner classes try { for (Class<?> innerClazz : clazz.getDeclaredClasses()) { if (classHasAnnotations(innerClazz)) { classList.add(innerClazz); } } } catch (Throwable t) { // amazingly, this sometimes throws an Error System.err.println("Could not load inner classes for: " + clazz); System.err.println(" " + t); continue; } } }
@SuppressWarnings("unchecked") public static YBEffect createTrail(Class<? extends YBEffect> effectClass, Entity entity) throws YiffBukkitCommandException { if (!effectClass.getAnnotation(EffectProperties.class).potionTrail()) return new NullEffect(); // Class.forName(effectClass.getCanonicalName()+".PotionTrail"); for (Class<?> enclosedClass : effectClass.getDeclaredClasses()) { if (enclosedClass.getSimpleName().equals("PotionTrail")) return create((Class<? extends YBEffect>) enclosedClass, entity); } throw new YiffBukkitCommandException( "Effect doesn't have a PotionTrail enclosed class but is flagged as having one."); }
private static void assertTestClassPresentByMetadata( @NotNull Class<?> outerClass, @NotNull File testDataDir) { for (Class<?> nestedClass : outerClass.getDeclaredClasses()) { TestMetadata testMetadata = nestedClass.getAnnotation(TestMetadata.class); if (testMetadata != null && testMetadata.value().equals(getFilePath(testDataDir))) { return; } } Assert.fail( "Test data directory missing from the generated test class: " + testDataDir + "\n" + PLEASE_REGENERATE_TESTS); }
private void reloadSource( @NotNull ClassDescriptorSourceUnit sourceFile, boolean detectInnerClasses) { Class clasz = customClassLoader.loadClass(sourceFile, true); LinkedList<ClassDescriptorInner> innerClassDescList = sourceFile.getInnerClassDescriptors(); if (innerClassDescList != null && !innerClassDescList.isEmpty()) { for (ClassDescriptorInner innerClassDesc : innerClassDescList) { customClassLoader.loadClass(innerClassDesc, true); } } else if (detectInnerClasses) { // Aprovechando la carga de la clase, hacemos el esfuerzo de cargar todas las clases // dependientes lo más // posible clasz .getDeclaredClasses(); // Provoca que las inner clases miembro indirectamente se procesen // y carguen // a través del JProxyClassLoader de la clase padre clasz // Ahora bien, lo anterior NO sirve para las anonymous inner classes, afortunadamente en ese // caso podemos // conocer y cargar por fuerza bruta // http://stackoverflow.com/questions/1654889/java-reflection-how-can-i-retrieve-anonymous-inner-classes // ?rq=1 for (int i = 1; i < Integer.MAX_VALUE; i++) { String anonClassName = sourceFile.getClassName() + "$" + i; Class innerClasz = customClassLoader.loadInnerClass(sourceFile, anonClassName); if (innerClasz == null) { break; // No hay más o no hay ninguna (si i es 1) } } // ¿Qué es lo que queda por cargar pero que no podemos hacer explícitamente? // 1) Las clases privadas autónomas que fueron definidas en el mismo archivo que la clase // principal: no // las soportamos pues no podemos identificar en el ClassLoader que es una clase "hot // reloadable", no son // inner classes en el sentido estricto // 2) Las clases privadas "inner" locales, es decir no anónimas declaradas dentro de un // método, se // cargarán la primera vez que se usen, no podemos conocerlas a priori // porque siguen la notación className$NclassName ej. // JReloadExampleDocument$1AuxMemberInMethod. No // hay problema con que se carguen con un class loader antiguo pues // el ClassLoader de la clase padre contenedora será el encargado de cargarla en cuanto se // pase por el // método que la declara. } }
private Operator<?>[] getSelfContainedOperators() { final List<Operator<?>> result = new ArrayList<>(); for (Class<?> c : ClassUtils.hierarchy(getClass(), interfacesPolicy)) { for (Class<?> inner : c.getDeclaredClasses()) { if (Operator.class.isAssignableFrom(inner)) { final Operator<?> operator = newInstance(inner.asSubclass(Operator.class)); if (operator != null) { result.add(operator); } } } } return result.toArray(new Operator[result.size()]); }
// Verify that all the fields of the inner classes of |R| have a valid mapping. // This ensures that if a resource is added upstream, we won't miss providing // a mapping downstream. private static void verifyFields(Class<?> R) { for (Class<?> c : R.getDeclaredClasses()) { verifyFields(c); // recursively check inner classes. } for (Field f : R.getDeclaredFields()) { try { if (f.getInt(null) == 0) { throw new RuntimeException( "Missing resource mapping for " + R.getName() + "." + f.getName()); } } catch (IllegalAccessException e) { } } }
public static void main(String[] args) throws Exception { Class<ClassTest> clazz = ClassTest.class; System.out.println("============================================="); Constructor[] ctors = clazz.getDeclaredConstructors(); System.out.println("classTest的全部构造器如下:"); for (Constructor c : ctors) { System.out.println(c); } System.out.println("============================================="); Constructor[] publicCtors = clazz.getConstructors(); System.out.println("ClassTest的全部public构造器如下:"); for (Constructor c : publicCtors) { System.out.println(c); } System.out.println("============================================="); Method[] mtds = clazz.getMethods(); System.out.println("ClassTest的全部public方法如下:"); for (Method md : mtds) { System.out.println(md); } System.out.println("============================================="); System.out.println("ClassTest带一个字符串参数的info方法为:" + clazz.getMethod("info", String.class)); Annotation[] ans = clazz.getAnnotations(); System.out.println("ClassTest的全部annotation为:"); for (Annotation an : ans) { System.out.println(an); } System.out.println("该元素上的@SuppressWarnings注释为:" + clazz.getAnnotation(SuppressWarnings.class)); System.out.println("============================================="); Class<?>[] inners = clazz.getDeclaredClasses(); System.out.println("ClassTest的全部内部类如下:"); for (Class c : inners) { System.out.println(c); } System.out.println("============================================="); Class inClazz = Class.forName("ClassTest$Inner"); System.out.println("inClazz对应的外部类为:" + inClazz.getDeclaringClass()); System.out.println("ClassTest的包为:" + clazz.getPackage()); System.out.println("ClassTest的父类:" + clazz.getSuperclass()); }
public static Map<String, byte[]> getResources(final Class<?>... classes) throws IOException { if (classes == null || classes.length == 0) { final String message = "No classes available"; throw new IOException(message); } final Map<String, byte[]> resources = new HashMap<String, byte[]>(); for (final Class<?> clazz : classes) { resources.put( clazz.getName().replace(".", "/") + ".class", ClassDataUtil.getClassData(clazz)); for (final Class<?> internalClass : clazz.getDeclaredClasses()) { resources.put( internalClass.getName().replace(".", "/") + ".class", ClassDataUtil.getClassData(internalClass)); } } return resources; }
private static String getSelect(final Class<?> klass) throws Exception { final SelectFrom from = klass.getAnnotation(SelectFrom.class); if (from != null) { return getSelectString(klass, from); } final Class<?>[] klasses = klass.getDeclaredClasses(); for (int i = 0; i < klasses.length; i++) { final String declared = getSelect(klasses[i]); if (!TextUtils.isEmpty(declared)) { return declared; } } return ""; }
/** * Recursively finds inner classes of the specified access level in the supplied class and * superclasses. * * @param c the class to start the search in - nothing is done if this is NULL * @param level the access level to look for * @param sb the StringBuffer where the results should be added */ private static void recursiveListInnerClasses(Class c, int level, StringBuffer sb) { if (c == null) { return; } Class[] innerClasses; Class innerClass; String clas; // ----- Added by Petter for interfaces if (level == PUBLIC) { // For public access, we can use getClasses() and skip // recursion. This ensures that the method works for // interface types, and saves some function calls. XXX - // actually, this doesn't work properly, since classes // defined in interfaces don't show up here. innerClasses = c.getClasses(); } else { innerClasses = c.getDeclaredClasses(); } // ----- End addition by Petter for (int index = 0; index < innerClasses.length; index++) { innerClass = innerClasses[index]; if (isAccessible(innerClass.getModifiers(), level)) { clas = printClass(innerClass.getName()); if (sb.toString().lastIndexOf(clas) == -1) { sb.append(clas); } } } // ----- Addition by Petter to reduce the number of function // calls and not list non-accessible private fields. if (!c.isInterface() && level != PRIVATE && level != PUBLIC) { // For interfaces, the getSuperClass() method will return // nil, and in any case, the only type of access relevant // for interfaces is PUBLIC. For PUBLIC access, the // getClasses() call has listed all the relevant members. // For PRIVATE access, that is only applicable in the // calling class anyway, so we shouldn't do recursion. recursiveListInnerClasses(c.getSuperclass(), level, sb); } // ----- End addition by Petter }
private boolean nestedClassRegistration( Named owner, Class<?> commands, Object instance, org.spout.api.command.Command parent) { boolean success = true, anyRegistered = false; for (Class<?> clazz : commands.getDeclaredClasses()) { Object subInstance = null; if (!Modifier.isStatic(clazz.getModifiers())) { try { Constructor<?> constr = getClosestConstructor(clazz, commands); if (constr == null) { continue; } constr.setAccessible(true); subInstance = constr.newInstance(instance); } catch (InvocationTargetException e) { e.printStackTrace(); continue; } catch (InstantiationException e) { e.printStackTrace(); continue; } catch (IllegalAccessException ignore) { } } org.spout.api.command.Command child = createCommand(owner, parent, clazz); if (child == null) { continue; } anyRegistered = true; if (!nestedClassRegistration(owner, clazz, subInstance, child)) { for (Method method : clazz.getDeclaredMethods()) { if (!method.isAnnotationPresent(Executor.class)) { continue; } Platform platform = method.getAnnotation(Executor.class).value(); child.setExecutor( platform, executorFactory.getAnnotatedCommandExecutor(subInstance, method)); } } } return success && anyRegistered; }
public PresenterRef(Class<?> presenterClass) { super(presenterClass); Class<?>[] internalClasses = presenterClass.getDeclaredClasses(); for (Class<?> internalClass : internalClasses) { if (View.class.isAssignableFrom(internalClass)) { viewInterface = internalClass; break; } } if (getWrappedClass().isAnnotationPresent(NameToken.class)) { nameToken = getWrappedClass().getAnnotation(NameToken.class).value(); } else { nameToken = ""; } this.disableCodeSplitting = getWrappedClass().isAnnotationPresent(DisableCodeSplit.class); }
public static Class<? extends Message> getInnerClass( String canonicalParentName, String subclassName) { try { Class<?> outerClass = Class.forName(canonicalParentName); for (Class<?> innerClass : outerClass.getDeclaredClasses()) { if (innerClass.getSimpleName().equals(subclassName)) { return innerClass.asSubclass(Message.class); } } } catch (ClassNotFoundException e) { LOG.error( "Could not find class with parent " + canonicalParentName + " and inner class " + subclassName, e); throw new IllegalArgumentException(e); } return null; }
public static void PrintInnerClasses(Class<?> cls) { System.out.println("Innerclasses for class: " + cls.getName()); Class<?>[] innerClasses = cls.getDeclaredClasses(); if (innerClasses.length == 0) { System.out.println("- None"); } else { for (Class<?> declaredClass : innerClasses) { System.out.println("- " + declaredClass.getName()); System.out.println("- is enum: " + declaredClass.isEnum()); // if (declaredClass.isEnum()) { Class<? extends Enum> enumClass = (Class<? extends Enum>) declaredClass; } // Annotation[] annotations = declaredClass.getAnnotations(); for (Annotation a : annotations) { System.out.println("- - with annotation: " + a.getClass().getName()); } } } }
public Collection<SourceClass> getMemberClasses() throws IOException { Object sourceToProcess = this.source; if (sourceToProcess instanceof Class<?>) { Class<?> sourceClass = (Class<?>) sourceToProcess; try { Class<?>[] declaredClasses = sourceClass.getDeclaredClasses(); List<SourceClass> members = new ArrayList<SourceClass>(declaredClasses.length); for (Class<?> declaredClass : declaredClasses) { members.add(asSourceClass(declaredClass)); } return members; } catch (NoClassDefFoundError err) { // getDeclaredClasses() failed because of non-resolvable dependencies // -> fall back to ASM below sourceToProcess = metadataReaderFactory.getMetadataReader(sourceClass.getName()); } } // ASM-based resolution - safe for non-resolvable classes as well MetadataReader sourceReader = (MetadataReader) sourceToProcess; String[] memberClassNames = sourceReader.getClassMetadata().getMemberClassNames(); List<SourceClass> members = new ArrayList<SourceClass>(memberClassNames.length); for (String memberClassName : memberClassNames) { try { members.add(asSourceClass(memberClassName)); } catch (IOException ex) { // Let's skip it if it's not resolvable - we're just looking for candidates if (logger.isDebugEnabled()) { logger.debug( "Failed to resolve member class [" + memberClassName + "] - not considering it as a configuration class candidate"); } } } return members; }