/** * model * * @param me */ @Override public void configPlugin(Plugins me) { componentSscan(basePackage); IDataSourceProvider iDataSourceProvider = setDataSource(); try { me.add((IPlugin) iDataSourceProvider); } catch (Exception e) { throw new RuntimeException("is not IPlugin type"); } ActiveRecordPlugin arp = new ActiveRecordPlugin(iDataSourceProvider); addActiveRecord(arp); // 加入附加的活动记录 Scan driven = new Scan(); for (String pake : basePackage) { Set<Class<?>> clazzs = driven.getClasses(pake); for (Class<?> clazz : clazzs) { LOG.info(clazz.getName()); Class superClass = clazz.getSuperclass(); Class<?> jfClz = com.jfinal.plugin.activerecord.Model.class; if (superClass == jfClz || superClass.getSuperclass() == jfClz) { M model = clazz.getAnnotation(M.class); if (null != model) { arp.addMapping(model.value(), model.id(), (Class<? extends Model<?>>) clazz); } } } } me.add(arp); }
private static Class<?>[] getObjectInterfaces(Class<?> objectClass, List<Class<?>> interfaces) { // Rq: object.getClass().getInterfaces() ne suffit pas pour Connection dans Tomcat // car la connection est une instance de PoolGuardConnectionWrapper // et connection.getClass().getInterfaces() est vide dans ce cas final List<Class<?>> myInterfaces; if (interfaces == null) { myInterfaces = new ArrayList<Class<?>>(Arrays.asList(objectClass.getInterfaces())); Class<?> classe = objectClass.getSuperclass(); while (classe != null) { final Class<?>[] classInterfaces = classe.getInterfaces(); if (classInterfaces.length > 0) { final List<Class<?>> superInterfaces = Arrays.asList(classInterfaces); // removeAll d'abord car il ne faut pas de doublon dans la liste myInterfaces.removeAll(superInterfaces); myInterfaces.addAll(superInterfaces); } classe = classe.getSuperclass(); } // on ignore l'interface javax.naming.Referenceable car sinon le rebind sous jetty appelle // referenceable.getReference() et devient inutile myInterfaces.remove(Referenceable.class); } else { myInterfaces = interfaces; } return myInterfaces.toArray(new Class<?>[myInterfaces.size()]); }
/** * reads all methods by the action-annotations for building agent-actions * * @param p_class class * @param p_root root class * @return stream of all methods with inheritance */ private static Stream<Method> methods(final Class<?> p_class, final Class<?> p_root) { final Pair<Boolean, IAgentAction.EAccess> l_classannotation = CCommon.isActionClass(p_class); if (!l_classannotation.getLeft()) return p_class.getSuperclass() == null ? Stream.of() : methods(p_class.getSuperclass(), p_root); final Predicate<Method> l_filter = IAgentAction.EAccess.WHITELIST.equals(l_classannotation.getRight()) ? i -> !CCommon.isActionFiltered(i, p_root) : i -> CCommon.isActionFiltered(i, p_root); return Stream.concat( Arrays.stream(p_class.getDeclaredMethods()) .parallel() .map( i -> { i.setAccessible(true); return i; }) .filter(i -> !Modifier.isAbstract(i.getModifiers())) .filter(i -> !Modifier.isInterface(i.getModifiers())) .filter(i -> !Modifier.isNative(i.getModifiers())) .filter(i -> !Modifier.isStatic(i.getModifiers())) .filter(l_filter), methods(p_class.getSuperclass(), p_root)); }
private void extractClassIntoMaps(Class type, boolean foundName, Supplier supplier) { if (type == null) { return; } String named = null; Class superClass = type.getSuperclass(); Class[] superTypes = type.getInterfaces(); for (Class superType : superTypes) { this.supplierTypeMap.put(superType, supplier); } while (superClass != Object.class) { this.supplierTypeMap.put(superClass, supplier); if (!foundName) { named = NamedUtils.namedValueForClass(superClass); if (named != null) { supplierNameMap.put(named, new ProviderInfo(named, type, supplier, null)); foundName = true; } } superTypes = type.getInterfaces(); for (Class superType : superTypes) { this.supplierTypeMap.put(superType, supplier); } superClass = superClass.getSuperclass(); } }
/** * Special helper function which allows for a map of default values. * * <p>First getString(directory,componentClass.getSimpleName(), null) is invoked, if the returned * value is null, the defaultMap is consulted for a value. * * @param directory * @param componentClass * @param defaultMap * @return */ protected String get( String directory, Class<? extends RocketComponent> componentClass, Map<Class<?>, String> defaultMap) { // Search preferences Class<?> c = componentClass; while (c != null && RocketComponent.class.isAssignableFrom(c)) { String value = this.getString(directory, c.getSimpleName(), null); if (value != null) return value; c = c.getSuperclass(); } if (defaultMap == null) return null; // Search defaults c = componentClass; while (RocketComponent.class.isAssignableFrom(c)) { String value = defaultMap.get(c); if (value != null) return value; c = c.getSuperclass(); } return null; }
@SuppressWarnings("unchecked") static Class<? extends Event<?>> getEventClass(Class<?> handlerClass) { for (Class<?> i : handlerClass.getInterfaces()) { if (EventHandler.class.equals(i)) { for (Type t : handlerClass.getGenericInterfaces()) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; if (EventHandler.class.equals(pt.getRawType())) { return (Class<? extends Event<?>>) pt.getActualTypeArguments()[0]; } } } } else if (EventHandler.class.isAssignableFrom(i)) { return getEventClass((Class<? extends EventHandler<?>>) i); } } if (EventHandler.class.isAssignableFrom(handlerClass.getSuperclass())) { return getEventClass((Class<?>) handlerClass.getSuperclass()); } return null; }
/** Looks inside the given class and finds all declared properties */ protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) { ArrayList<Property<?>> properties = new ArrayList<>(); if (cls.getSuperclass() != AbstractModel.class) { properties.addAll( Arrays.asList(generateProperties((Class<? extends AbstractModel>) cls.getSuperclass()))); } // a property is public, static & extends Property for (Field field : cls.getFields()) { if ((field.getModifiers() & Modifier.STATIC) == 0) { continue; } if (!Property.class.isAssignableFrom(field.getType())) { continue; } try { if (((Property<?>) field.get(null)).table == null) { continue; } properties.add((Property<?>) field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } return properties.toArray(new Property<?>[properties.size()]); }
public void postInitialize(Set<Class<?>> indexedClasses) { // we initialize only once because we no longer have a reference to the reflectionManager // in theory Class<?> plainClass = beanClass; if (entityState == EntityState.NON_INDEXABLE) { throw new AssertionFailure("A non indexed entity is post processed"); } Set<Class<?>> tempMappedSubclasses = new HashSet<Class<?>>(); // together with the caller this creates a o(2), but I think it's still faster than create the // up hierarchy for each class for (Class<?> currentClass : indexedClasses) { if (plainClass != currentClass && plainClass.isAssignableFrom(currentClass)) { tempMappedSubclasses.add(currentClass); } } this.mappedSubclasses = Collections.unmodifiableSet(tempMappedSubclasses); Class<?> superClass = plainClass.getSuperclass(); this.isRoot = true; while (superClass != null) { if (indexedClasses.contains(superClass)) { this.isRoot = false; break; } superClass = superClass.getSuperclass(); } }
private void sortPotentialOption(Class<? extends Option> probableOption) { Class superClass = probableOption.getSuperclass(); while (true) { if (superClass == Pattern.class) { patterns.add(probableOption); break; } if (superClass == Condition.class) { conditions.add(probableOption); break; } if (superClass == Action.class) { actions.add(probableOption); break; } if (superClass == Requirement.class) { requirements.add(probableOption); break; } if (superClass == Object.class) { break; } superClass = superClass.getSuperclass(); } }
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 static void print(Class<?> clazz) { if (WarpCommons.debugMode()) { System.out.println(); System.out.println("Class: " + clazz.getName()); System.out.println( "SuperClass: " + clazz.getSuperclass() + " " + clazz.getSuperclass().hashCode()); System.out.println("Interfaces: " + Arrays.asList(clazz.getInterfaces())); System.out.println("Fields"); for (Field field : clazz.getDeclaredFields()) { printAnnotation(field); System.out.println("\t" + field); } System.out.println("Constructors"); for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { printAnnotation(constructor); System.out.println("\t" + constructor); } System.out.println("Methods"); for (Method method : clazz.getDeclaredMethods()) { printAnnotation(method); System.out.println("\t" + method); } } }
private void generateStage( Element[] parents, Class stage, Set<Class<? extends Stage>> generatedStages) { if (generatedStages.contains(stage)) return; boolean hasParentStage = Stage.class.isAssignableFrom(stage.getSuperclass()); if (hasParentStage) { generateStage(parents, stage.getSuperclass(), generatedStages); } org.radargun.config.Stage stageAnnotation = (org.radargun.config.Stage) stage.getAnnotation(org.radargun.config.Stage.class); if (stageAnnotation == null) return; // not a proper stage String stageType = generateClass(stage); if (!Modifier.isAbstract(stage.getModifiers()) && !stageAnnotation.internal()) { for (Element parent : parents) { createReference( parent, XmlHelper.camelCaseToDash(StageHelper.getStageName(stage)), stageType); } if (!stageAnnotation.deprecatedName().equals(org.radargun.config.Stage.NO_DEPRECATED_NAME)) { for (Element parent : parents) { createReference( parent, XmlHelper.camelCaseToDash(stageAnnotation.deprecatedName()), stageType); } } } generatedStages.add(stage); }
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); } } }
private static void superclasses(Class c, Collection results) { if (c.getSuperclass() == null) { return; } results.add(c.getSuperclass()); superclasses(c.getSuperclass(), results); }
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 MessageFormatter lookup(Class<?> clazz) { MessageFormatter formatter = cMessageFormatters.get(clazz); if (formatter == null) { String className = clazz.getName(); String resourcesName; int index = className.lastIndexOf('.'); if (index >= 0) { resourcesName = className.substring(0, index + 1) + "resources." + className.substring(index + 1); } else { resourcesName = "resources." + className; } try { formatter = new MessageFormatter(ResourceBundle.getBundle(resourcesName)); } catch (MissingResourceException e) { if (clazz.getSuperclass() == null) { throw e; } try { formatter = lookup(clazz.getSuperclass()); } catch (MissingResourceException e2) { throw e; } } cMessageFormatters.put(clazz, formatter); } return formatter; }
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (out.addRef(obj)) return; Class cl = obj.getClass(); if (!cl.isEnum() && cl.getSuperclass().isEnum()) cl = cl.getSuperclass(); String name = null; try { name = (String) _name.invoke(obj, (Object[]) null); } catch (Exception e) { throw new RuntimeException(e); } int ref = out.writeObjectBegin(cl.getName()); if (ref < -1) { out.writeString("name"); out.writeString(name); out.writeMapEnd(); } else { if (ref == -1) { out.writeClassFieldLength(1); out.writeString("name"); out.writeObjectBegin(cl.getName()); } out.writeString(name); } }
/*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) { // cannot use Util.isOverridden as these are protected methods. boolean hasGetNodes = false; boolean hasMatches = false; while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) { if (!hasGetNodes) { try { final Method getNodes = clazz.getDeclaredMethod("getNodes"); hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!hasMatches) { try { final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class); hasMatches = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) { clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass(); } } return hasGetNodes && hasMatches; }
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); }
/** * get value from object via calling getter method. * * @param property * @param model * @return */ public static Object get(String property, Object model) { try { Class<?> clazz = model.getClass(); Method method = null; while (clazz != null) { try { Field field = getField(property, model); String getterName = getterName(property, field.getType() == boolean.class); method = clazz.getDeclaredMethod(getterName); } catch (NoSuchMethodException e) { clazz = clazz.getSuperclass(); continue; } if (method != null) { return method.invoke(model); } clazz = clazz.getSuperclass(); } if (method == null) { throw new RuntimeException("cannot find getter method for property " + property); } return null; } catch (Exception e) { throw new RuntimeException(e); } }
private static ButterKnife.Injector<Object> findInjectorForClass(Class<?> paramClass) { Object localObject = (ButterKnife.Injector)INJECTORS.get(paramClass); if (localObject != null) { return (ButterKnife.Injector<Object>)localObject; } localObject = paramClass.getName(); if ((((String)localObject).startsWith("android.")) || (((String)localObject).startsWith("java."))) { return NOP_INJECTOR; } try { localObject = (ButterKnife.Injector)Class.forName((String)localObject + "$$ViewInjector").newInstance(); INJECTORS.put(paramClass, localObject); return (ButterKnife.Injector<Object>)localObject; } catch (ClassNotFoundException localClassNotFoundException) { for (;;) { if (debug) { new StringBuilder().append("Not found. Trying superclass ").append(paramClass.getSuperclass().getName()).toString(); } ButterKnife.Injector localInjector = findInjectorForClass(paramClass.getSuperclass()); } } }
protected void testListenerAddGetRemove( Class<?> cls, Class<?> eventClass, Class<?> listenerClass, Object c) throws Exception { Object mockListener1 = EasyMock.createMock(listenerClass); Object mockListener2 = EasyMock.createMock(listenerClass); // Verify we start from no listeners verifyListeners(c, eventClass); // Add one listener and verify addListener(c, mockListener1, listenerClass); verifyListeners(c, eventClass, mockListener1); // Add another listener and verify addListener(c, mockListener2, listenerClass); verifyListeners(c, eventClass, mockListener1, mockListener2); // Ensure we can fetch using parent class also if (eventClass.getSuperclass() != null) { verifyListeners(c, eventClass.getSuperclass(), mockListener1, mockListener2); } // Remove the first and verify removeListener(c, mockListener1, listenerClass); verifyListeners(c, eventClass, mockListener2); // Remove the remaining and verify removeListener(c, mockListener2, listenerClass); verifyListeners(c, eventClass); }
private static ArrayList<ClassFields> getFields(Class<?> klass) { if (klass == null || klass.getSuperclass() == null) return new ArrayList<ClassFields>(); ArrayList<ClassFields> cFields = getFields(klass.getSuperclass()); cFields.add(new ClassFields(klass)); return cFields; }
private Object getBeanObject(final Class<?> classType) throws ClassNotFoundException { final List<Class<?>> typesList = new ArrayList<>(); final Class<?>[] interfaceType = classType.getInterfaces(); if (interfaceType.length > 0) { typesList.addAll(Arrays.asList(interfaceType)); } else { Class<?> superclassType = classType; while (!Object.class.getName().equals(superclassType.getSuperclass().getName())) { superclassType = superclassType.getSuperclass(); } typesList.add(superclassType); } final List<String> beanNames = new ArrayList<>(); for (final Class<?> clazz : typesList) { beanNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(clazz))); } Object targetObject = null; for (final String beanName : beanNames) { final Object nextObject = this.applicationContext.getBean(beanName); String targetObjName = nextObject.toString(); targetObjName = targetObjName.substring(0, targetObjName.lastIndexOf("@")); if (classType.getName().equals(targetObjName)) { targetObject = nextObject; break; } } return targetObject; }
private Object findAncestor(Class<?> clazz) { // First check enclosing classes Class<?> c = clazz.getDeclaringClass(); while (c != null) { if (c.isAnnotationPresent(Gwtc.class)) { return c; } c = c.getDeclaringClass(); } Package p = clazz.getPackage(); if (p.getAnnotation(Gwtc.class) != null) { return p; } Object o = findAncestor(p); if (o == null) { c = clazz.getSuperclass(); while (c != null) { if (c.isAnnotationPresent(Gwtc.class)) { return c; } c = c.getSuperclass(); } } return o; }
private Class getAnnotationType(Class cl) { if (cl == null) { return null; } if (Annotation.class.equals(cl.getSuperclass())) { return cl; } Class ifaces[] = cl.getInterfaces(); if (ifaces != null) { for (Class iface : ifaces) { if (iface.equals(Annotation.class)) { return cl; } Class annType = getAnnotationType(iface); if (annType != null) { return annType; } } } return getAnnotationType(cl.getSuperclass()); }
private void addFields(Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (canAccessPrivateMethods()) { try { field.setAccessible(true); } catch (Exception e) { // Ignored. This is only a final precaution, nothing we can do. } } if (field.isAccessible()) { if (!setMethods.containsKey(field.getName())) { // issue #379 - removed the check for final because JDK 1.5 allows // modification of final fields through reflection (JSR-133). (JGB) // pr #16 - final static can only be set by the classloader int modifiers = field.getModifiers(); if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) { addSetField(field); } } if (!getMethods.containsKey(field.getName())) { addGetField(field); } } } if (clazz.getSuperclass() != null) { addFields(clazz.getSuperclass()); } }
@Override public synchronized T get(Object key) { Class<?> clazz = (Class<?>) key; if (_cache.containsKey(clazz)) { // Could be null return _cache.get(key); } if (clazz.getSuperclass() != null) { T value = get(clazz.getSuperclass()); if (value != null) { addValueToCache(clazz, value); return value; } } for (Class<?> intface : clazz.getInterfaces()) { T value = get(intface); if (value != null) { addValueToCache(clazz, value); return value; } } addValueToCache(clazz, null); return null; }
/** * controller * * @param me */ @Override public void configRoute(Routes me) { // String path = this.getClass().getClassLoader().getResource("").getPath(); controlSscan(controlPackage); // 获取需要扫描的包 // 扫描器 Scan driven = new Scan(); for (String pake : controlPackage) { Set<Class<?>> clazzs = driven.getClasses(pake); /*System.out.println("pake: " + pake);*/ for (Class<?> clazz : clazzs) { // System.out.println(clazz.getSuperclass()); LOG.info(clazz.getName()); Class<?> superclass = clazz.getSuperclass(); Class<?> jfClz = com.jfinal.core.Controller.class; if (superclass == jfClz || superclass.getSuperclass() == jfClz) { C con = clazz.getAnnotation(C.class); if (null != con) { me.add(con.value(), (Class<? extends Controller>) clazz); } } } } }
/* * TODO: Profiling shows that the reflection and conditional logic in this * method is a hotspot. This could be remedied by generating synthetic * InstantiateCommand types that initialize themselves. */ private IdentityValueCommand makeObject(Class<?> type, Object value) throws SerializationException { if (type.isAnonymousClass() || type.isLocalClass()) { throw new SerializationException("Cannot serialize anonymous or local classes"); } Class<?> manualType = type; Class<?> customSerializer; do { customSerializer = SerializabilityUtil.hasCustomFieldSerializer(manualType); if (customSerializer != null) { break; } manualType = manualType.getSuperclass(); } while (manualType != null); IdentityValueCommand ins; if (customSerializer != null) { ins = serializeWithCustomSerializer(customSerializer, value, type, manualType); } else { ins = new InstantiateCommand(type); identityMap.put(value, ins); } /* * If we're looking at a subclass of a manually-serialized type, the * subclass must be tagged as serializable in order to qualify for * serialization. */ if (type != manualType) { if (!Serializable.class.isAssignableFrom(type) && !IsSerializable.class.isAssignableFrom(type)) { throw new SerializationException(type.getName() + " is not a serializable type"); } } while (type != manualType) { Field[] serializableFields = clientOracle.getOperableFields(type); for (Field declField : serializableFields) { assert (declField != null); Accessor accessor = CommandSerializationUtil.getAccessor(declField.getType()); ValueCommand valueCommand; Object fieldValue = accessor.get(value, declField); if (fieldValue == null) { valueCommand = NullValueCommand.INSTANCE; } else { Class<? extends Object> fieldType = declField.getType().isPrimitive() ? declField.getType() : fieldValue.getClass(); valueCommand = makeValue(fieldType, fieldValue); } ((HasSetters) ins).set(declField.getDeclaringClass(), declField.getName(), valueCommand); } type = type.getSuperclass(); } return ins; }