List of usage examples for java.lang.reflect Modifier isInterface
public static boolean isInterface(int mod)
From source file:org.datavec.api.transform.TransformProcess.java
private static ObjectMapper reinitializeMapperWithSubtypes(ObjectMapper mapper) { //Register concrete subtypes for JSON serialization List<Class<?>> classes = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<String> classNames = new ArrayList<>(6); for (Class<?> c : classes) classNames.add(c.getName());/* ww w. j a v a 2 s . c o m*/ // First: scan the classpath and find all instances of the 'baseClasses' classes if (subtypesClassCache == null) { List<Class<?>> interfaces = Arrays.<Class<?>>asList(Transform.class, Condition.class, Filter.class, IReducer.class); List<Class<?>> classesList = Arrays.<Class<?>>asList(); Collection<URL> urls = ClasspathHelper.forClassLoader(); List<URL> scanUrls = new ArrayList<>(); for (URL u : urls) { String path = u.getPath(); if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs scanUrls.add(u); } } Reflections reflections = new Reflections( new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc //Exclude the following: the assumption here is that no custom functionality will ever be present // under these package name prefixes. .exclude("^org.nd4j.*").exclude("^org.bytedeco.*") //JavaCPP .exclude("^com.fasterxml.*")//Jackson .exclude("^org.apache.*") //Apache commons, Spark, log4j etc .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*").exclude("^org.joda.*") .exclude("^org.slf4j.*").exclude("^com.google.*").exclude("^org.reflections.*") .exclude("^ch.qos.*") //Logback ).addUrls(scanUrls).setScanners(new DataVecSubTypesScanner(interfaces, classesList))); org.reflections.Store store = reflections.getStore(); Iterable<String> subtypesByName = store.getAll(DataVecSubTypesScanner.class.getSimpleName(), classNames); Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName)); subtypesClassCache = new HashSet<>(); for (Class<?> c : subtypeClasses) { if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } subtypesClassCache.add(c); } } //Second: get all currently registered subtypes for this mapper Set<Class<?>> registeredSubtypes = new HashSet<>(); for (Class<?> c : classes) { AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(), null); Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector()); for (NamedType nt : types) { registeredSubtypes.add(nt.getType()); } } //Third: register all _concrete_ subtypes that are not already registered List<NamedType> toRegister = new ArrayList<>(); for (Class<?> c : subtypesClassCache) { //Check if it's concrete or abstract... if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } if (!registeredSubtypes.contains(c)) { String name; if (ClassUtils.isInnerClass(c)) { Class<?> c2 = c.getDeclaringClass(); name = c2.getSimpleName() + "$" + c.getSimpleName(); } else { name = c.getSimpleName(); } toRegister.add(new NamedType(c, name)); if (log.isDebugEnabled()) { for (Class<?> baseClass : classes) { if (baseClass.isAssignableFrom(c)) { log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(), baseClass.getName()); break; } } } } } mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()])); //Recreate the mapper (via copy), as mapper won't use registered subtypes after first use mapper = mapper.copy(); return mapper; }
From source file:org.kuali.rice.krad.service.impl.RemoteModuleServiceBase.java
/** * @see org.kuali.rice.krad.service.ModuleService#getExternalizableBusinessObjectImplementation(java.lang.Class) *///from www.j a v a 2 s . c o m @Override public <E extends ExternalizableBusinessObject> Class<E> getExternalizableBusinessObjectImplementation( Class<E> externalizableBusinessObjectInterface) { if (getModuleConfiguration() == null) { throw new IllegalStateException( "Module configuration has not been initialized for the module service."); } Map<Class, Class> ebos = getModuleConfiguration().getExternalizableBusinessObjectImplementations(); if (ebos == null) { return null; } if (ebos.containsValue(externalizableBusinessObjectInterface)) { return externalizableBusinessObjectInterface; } else { Class<E> implementationClass = ebos.get(externalizableBusinessObjectInterface); int implClassModifiers = implementationClass.getModifiers(); if (Modifier.isInterface(implClassModifiers) || Modifier.isAbstract(implClassModifiers)) { throw new RuntimeException("Implementation class must be non-abstract class: ebo interface: " + externalizableBusinessObjectInterface.getName() + " impl class: " + implementationClass.getName() + " module: " + getModuleConfiguration().getNamespaceCode()); } return implementationClass; } }
From source file:org.dd4t.databind.builder.json.JsonModelConverter.java
private <T extends BaseViewModel> BaseViewModel buildModelForField(final JsonNode currentField, final Class<T> modelClassToUse) throws SerializationException { if (Modifier.isAbstract(modelClassToUse.getModifiers()) || Modifier.isInterface(modelClassToUse.getModifiers())) { // Get root element name final String rootElementName = getRootElementNameFromComponentOrEmbeddedField(currentField); if (StringUtils.isNotEmpty(rootElementName)) { // attempt get a concrete class for this interface final Class<? extends BaseViewModel> concreteClass = databinder .getConcreteModel(modelClassToUse.getCanonicalName(), rootElementName); if (concreteClass == null) { LOG.error("Attempt to find a concrete model class for interface or abstract class: {} failed " + "miserably as there was no registered class for root element name: '{}' Will return null" + ".", modelClassToUse.getCanonicalName(), rootElementName); return null; }// w ww . j ava 2 s .co m LOG.debug("Building: {}", concreteClass.getCanonicalName()); return getBaseViewModel(currentField, concreteClass); } else { LOG.error( "Attempt to find a concrete model class for interface or abstract class: {} failed " + "miserably as a root element name could not be found. Will return null.", modelClassToUse.getCanonicalName()); return null; } } else { return getBaseViewModel(currentField, modelClassToUse); } }
From source file:org.latticesoft.util.common.StringUtil.java
/** * Print the properties of an object into a xml string. * This is useful in the object's toString method. * @param o the object to be converted/*from ww w .ja v a2 s . com*/ * @param mode one of the above mode * @param displayAll display all attributes including those which are null. * @return the string-fied xml form of the object */ public static String formatObjectToXmlString(Object o, int mode, boolean displayAll) { if (o == null) return "<NullClass/>"; StringBuffer sb = new StringBuffer(); String s = o.getClass().getName(); String p = o.getClass().getPackage().getName(); String className = s.substring(p.length() + 1, s.length()); if (mode == StringUtil.MODE_END_TAG) { sb.append("</"); sb.append(className); sb.append(">"); return sb.toString(); } sb.append("<"); sb.append(className); // list of attributes Field f[] = o.getClass().getDeclaredFields(); WrapDynaBean dyn = null; try { dyn = new WrapDynaBean(o); } catch (Exception e) { } for (int i = 0; i < f.length; i++) { String name = f[i].getName(); int modifier = f[i].getModifiers(); if (Modifier.isFinal(modifier) || Modifier.isAbstract(modifier) || Modifier.isInterface(modifier) || Modifier.isStatic(modifier)) { continue; } Object value = null; try { value = dyn.get(name); } catch (Exception e) { //if (log.isErrorEnabled()) { log.error(e); } } if (name != null) { if ((value != null && !displayAll) || (displayAll)) { sb.append(" "); sb.append(name); sb.append("=\""); sb.append(value); sb.append("\""); } } } switch (mode) { default: case StringUtil.MODE_FULL_STANDARD: sb.append("/>"); break; case StringUtil.MODE_FULL_LONG: sb.append("></"); sb.append(className); sb.append(">"); break; case StringUtil.MODE_START_TAG: sb.append(">"); break; } return sb.toString(); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
/** * Between two getter methods defined for a given property, both declared in the same class, picks one * * @param first the first getter/*from w w w . j a v a 2 s . c o m*/ * @param second the second getter * @return the winning getter */ private static Method pickGetter(Method first, Method second) { //if one is an interface, and one is not, the concrete implementation wins if (Modifier.isInterface(first.getModifiers()) && !Modifier.isInterface(second.getModifiers())) { return second; } if (!Modifier.isInterface(first.getModifiers()) && Modifier.isInterface(second.getModifiers())) { return first; } //if one is abstract and the other is not, the non-abstract one wins if (Modifier.isAbstract(first.getModifiers()) && !Modifier.isAbstract(second.getModifiers())) { return second; } if (!Modifier.isAbstract(first.getModifiers()) && Modifier.isAbstract(second.getModifiers())) { return first; } //given a hierarchy, the child wins if (first.getReturnType().isAssignableFrom(second.getReturnType())) { return second; } if (second.getReturnType().isAssignableFrom(first.getReturnType())) { return first; } if (!hasAnnotations(first) && hasAnnotations(second)) { return second; } if (hasAnnotations(first) && !hasAnnotations(second)) { return first; } return first; }
From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java
@SuppressWarnings("unchecked") public static <X> TypeInformation<X> getForClass(Class<X> clazz) { Validate.notNull(clazz);//from w ww .ja v a2 s.c om // check for abstract classes or interfaces if (Modifier.isInterface(clazz.getModifiers()) || (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray())) { throw new InvalidTypesException("Interfaces and abstract classes are not valid types."); } // check for arrays if (clazz.isArray()) { // primitive arrays: int[], byte[], ... PrimitiveArrayTypeInfo<X> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz); if (primitiveArrayInfo != null) { return primitiveArrayInfo; } // basic type arrays: String[], Integer[], Double[] BasicArrayTypeInfo<X, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz); if (basicArrayInfo != null) { return basicArrayInfo; } // object arrays else { return ObjectArrayTypeInfo.getInfoFor(clazz); } } // check for writable types if (Writable.class.isAssignableFrom(clazz)) { return (TypeInformation<X>) WritableTypeInfo.getWritableTypeInfo((Class<? extends Writable>) clazz); } // check for basic types TypeInformation<X> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz); if (basicTypeInfo != null) { return basicTypeInfo; } // check for subclasses of Value if (Value.class.isAssignableFrom(clazz)) { Class<? extends Value> valueClass = clazz.asSubclass(Value.class); return (TypeInformation<X>) ValueTypeInfo.getValueTypeInfo(valueClass); } // check for subclasses of Tuple if (Tuple.class.isAssignableFrom(clazz)) { throw new InvalidTypesException( "Type information extraction for tuples cannot be done based on the class."); } // return a generic type return new GenericTypeInfo<X>(clazz); }
From source file:org.zaproxy.zap.control.AddOnLoader.java
public <T> List<T> getImplementors(AddOn ao, String packageName, Class<T> classType) { Class<?> cls = null;// w ww . j a v a2 s .co m List<T> listClass = new ArrayList<>(); List<ClassNameWrapper> classNames; if (ao != null) { classNames = this.getJarClassNames(ao, packageName); } else { classNames = this.getClassNames(packageName, classType); } for (ClassNameWrapper classWrapper : classNames) { try { cls = classWrapper.getCl().loadClass(classWrapper.getClassName()); // abstract class or interface cannot be constructed. if (Modifier.isAbstract(cls.getModifiers()) || Modifier.isInterface(cls.getModifiers())) { continue; } if (classType.isAssignableFrom(cls)) { @SuppressWarnings("unchecked") Constructor<T> c = (Constructor<T>) cls.getConstructor(); listClass.add(c.newInstance()); } } catch (Throwable e) { // Often not an error logger.debug(e.getMessage()); } } return listClass; }
From source file:org.latticesoft.util.common.StringUtil.java
public static String formatObjectToString(Object o, boolean includeChild) { if (o == null) return ""; if (o == null) return ""; StringBuffer sb = new StringBuffer(); String className = o.getClass().getName(); sb.append("["); sb.append(className);/* w ww. java2s . c o m*/ sb.append("|"); // list of attributes Field f[] = o.getClass().getDeclaredFields(); WrapDynaBean dyn = null; try { dyn = new WrapDynaBean(o); } catch (Exception e) { } for (int i = 0; i < f.length; i++) { String name = f[i].getName(); int modifier = f[i].getModifiers(); if (Modifier.isFinal(modifier) || Modifier.isAbstract(modifier) || Modifier.isInterface(modifier) || Modifier.isStatic(modifier)) { continue; } Object value = null; try { value = dyn.get(name); } catch (Exception e) { //if (log.isErrorEnabled()) { log.error(e); } } if (name != null && value != null) { sb.append(name); sb.append("="); if (value instanceof Map) { Map map = (Map) value; if (includeChild) { sb.append(value); } else { sb.append(map.size()); } sb.append("|"); } else if (value instanceof Collection) { Collection c = (Collection) value; if (includeChild) { sb.append(value); } else { sb.append(c.size()); } sb.append("|"); } else { sb.append(value); sb.append("|"); } } } sb.deleteCharAt(sb.length() - 1); sb.append("]"); return sb.toString(); }
From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java
@Override @SuppressWarnings("unchecked") public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype, ArgumentMatches matches) {/* w w w . j a v a 2 s. c om*/ Class type = makeRawTypeIfNecessary(fulltype); Type componentType; Object result; if (Collection.class.isAssignableFrom(type)) { // If this is a generic interface, pick a concrete implementation to create and pass back. // Because of type erasure, don't worry about creating one of exactly the correct type. if (Modifier.isInterface(type.getModifiers()) || Modifier.isAbstract(type.getModifiers())) { if (java.util.List.class.isAssignableFrom(type)) type = ArrayList.class; else if (java.util.Queue.class.isAssignableFrom(type)) type = java.util.ArrayDeque.class; else if (java.util.Set.class.isAssignableFrom(type)) type = java.util.TreeSet.class; } componentType = getCollectionComponentType(source.field); ArgumentTypeDescriptor componentArgumentParser = parsingEngine .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType)); Collection collection; try { collection = (Collection) type.newInstance(); } catch (InstantiationException e) { logger.fatal( "ArgumentParser: InstantiationException: cannot convert field " + source.field.getName()); throw new ReviewedStingException( "constructFromString:InstantiationException: Failed conversion " + e.getMessage()); } catch (IllegalAccessException e) { logger.fatal( "ArgumentParser: IllegalAccessException: cannot convert field " + source.field.getName()); throw new ReviewedStingException( "constructFromString:IllegalAccessException: Failed conversion " + e.getMessage()); } for (ArgumentMatch match : matches) { for (ArgumentMatch value : match) { Object object = componentArgumentParser.parse(parsingEngine, source, componentType, new ArgumentMatches(value)); collection.add(object); // WARNING: Side effect! parsingEngine.addTags(object, value.tags); } } result = collection; } else if (type.isArray()) { componentType = type.getComponentType(); ArgumentTypeDescriptor componentArgumentParser = parsingEngine .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType)); // Assemble a collection of individual values used in this computation. Collection<ArgumentMatch> values = new ArrayList<ArgumentMatch>(); for (ArgumentMatch match : matches) for (ArgumentMatch value : match) values.add(value); result = Array.newInstance(makeRawTypeIfNecessary(componentType), values.size()); int i = 0; for (ArgumentMatch value : values) { Object object = componentArgumentParser.parse(parsingEngine, source, componentType, new ArgumentMatches(value)); Array.set(result, i++, object); // WARNING: Side effect! parsingEngine.addTags(object, value.tags); } } else throw new ReviewedStingException("Unsupported compound argument type: " + type); return result; }
From source file:ca.oson.json.Oson.java
private boolean ignoreModifiers(int modifiers, Set<MODIFIER> includeFieldsWithModifiers) { //Set<MODIFIER> includeFieldsWithModifiers = getIncludeFieldsWithModifiers(); if (includeFieldsWithModifiers == null || includeFieldsWithModifiers.size() == 0) { // by default, transient and volatile are ignored // unless you specify otherwise, by using MODIFIER.Transient enum, or all if (Modifier.isTransient(modifiers)) { return true; }/* w w w . jav a 2 s.c om*/ if (Modifier.isVolatile(modifiers)) { return true; } return false; } if (includeFieldsWithModifiers.contains(MODIFIER.All)) { return false; } for (MODIFIER modifier : includeFieldsWithModifiers) { switch (modifier) { case Abstract: if (Modifier.isAbstract(modifiers)) { return false; } break; case Final: if (Modifier.isFinal(modifiers)) { return false; } break; case Interface: if (Modifier.isInterface(modifiers)) { return false; } break; case Native: if (Modifier.isNative(modifiers)) { return false; } break; case Private: if (Modifier.isPrivate(modifiers)) { return false; } break; case Protected: if (Modifier.isProtected(modifiers)) { return false; } break; case Public: if (Modifier.isPublic(modifiers)) { return false; } break; case Package: if (ObjectUtil.isPackage(modifiers)) { return false; } break; case Static: if (Modifier.isStatic(modifiers)) { return false; } break; case Strict: if (Modifier.isStrict(modifiers)) { return false; } break; case Synchronized: if (Modifier.isSynchronized(modifiers)) { return false; } break; case Transient: if (Modifier.isTransient(modifiers)) { return false; } break; case Volatile: if (Modifier.isVolatile(modifiers)) { return false; } break; } } return true; }