List of usage examples for java.lang.reflect Modifier isAbstract
public static boolean isAbstract(int mod)
From source file:jp.co.acroquest.jsonic.JSON.java
protected <T> T create(Context context, Class<? extends T> c) throws Exception { Object instance = null;//from w ww .j a v a2 s .c o m JSONHint hint = context.getHint(); if (hint != null && hint.type() != Object.class) c = hint.type().asSubclass(c); if (c.isInterface()) { if (SortedMap.class.equals(c)) { instance = new TreeMap<Object, Object>(); } else if (Map.class.equals(c)) { instance = new LinkedHashMap<Object, Object>(); } else if (SortedSet.class.equals(c)) { instance = new TreeSet<Object>(); } else if (Set.class.equals(c)) { instance = new LinkedHashSet<Object>(); } else if (List.class.equals(c)) { instance = new ArrayList<Object>(); } else if (Collection.class.equals(c)) { instance = new ArrayList<Object>(); } else if (Appendable.class.equals(c)) { instance = new StringBuilder(); } } else if (Modifier.isAbstract(c.getModifiers())) { if (Calendar.class.equals(c)) { instance = Calendar.getInstance(); } } else if ((c.isMemberClass() || c.isAnonymousClass()) && !Modifier.isStatic(c.getModifiers())) { Class<?> eClass = c.getEnclosingClass(); Constructor<?> con = c.getDeclaredConstructor(eClass); con.setAccessible(true); if (context.contextObject != null && eClass.isAssignableFrom(context.contextObject.getClass())) { instance = con.newInstance(context.contextObject); } else { instance = con.newInstance((Object) null); } } else { if (Date.class.isAssignableFrom(c)) { try { Constructor<?> con = c.getDeclaredConstructor(long.class); con.setAccessible(true); instance = con.newInstance(0l); } catch (NoSuchMethodException e) { // no handle } } if (instance == null) { Constructor<?> con = c.getDeclaredConstructor(); con.setAccessible(true); instance = con.newInstance(); } } return c.cast(instance); }
From source file:org.apache.openjpa.meta.ClassMetaData.java
/** * Make sure the application identity class is valid. *///from ww w . ja v a 2 s . com private void validateAppIdClass() { // base types must declare an oid class if not single-field identity FieldMetaData[] pks = getPrimaryKeyFields(); if (getObjectIdType() == null) { if (pks.length == 1) throw new MetaDataException(_loc.get("unsupported-id-type", _type, pks[0].getName(), pks[0].getDeclaredType().getName())); throw new MetaDataException(_loc.get("no-id-class", _type, Arrays.asList(toNames(pks)))); } if (_objectId == null) return; if (isOpenJPAIdentity()) { if (pks[0].getDeclaredTypeCode() == JavaTypes.OID) { ClassMetaData embed = pks[0].getEmbeddedMetaData(); validateAppIdClassMethods(embed.getDescribedType()); validateAppIdClassPKs(embed, embed.getFields(), embed.getDescribedType()); } return; } if (_super != null) { // concrete superclass oid must match or be parent of ours ClassMetaData sup = getPCSuperclassMetaData(); Class<?> objectIdType = sup.getObjectIdType(); if (objectIdType != null && !objectIdType.isAssignableFrom(_objectId)) throw new MetaDataException( _loc.get("id-classes", new Object[] { _type, _objectId, _super, sup.getObjectIdType() })); // validate that no other pks are declared if we have a // concrete PC superclass if (hasConcretePCSuperclass()) validateNoPKFields(); } // if this class has its own oid class, do some more validation if (_super == null || _objectId != getPCSuperclassMetaData().getObjectIdType()) { // make sure non-abstract oid classes override the proper methods if (!Modifier.isAbstract(_objectId.getModifiers())) validateAppIdClassMethods(_objectId); // make sure the application id class has all primary key fields validateAppIdClassPKs(this, pks, _objectId); } }
From source file:org.apache.hive.beeline.BeeLine.java
Driver[] scanDrivers(boolean knownOnly) throws IOException { long start = System.currentTimeMillis(); Set<String> classNames = new HashSet<String>(); if (!knownOnly) { classNames.addAll(Arrays.asList(ClassNameCompleter.getClassNames())); }/*w w w.j a v a 2s.c o m*/ classNames.addAll(KNOWN_DRIVERS); Set driverClasses = new HashSet(); for (Iterator<String> i = classNames.iterator(); i.hasNext();) { String className = i.next().toString(); if (className.toLowerCase().indexOf("driver") == -1) { continue; } try { Class c = Class.forName(className, false, Thread.currentThread().getContextClassLoader()); if (!Driver.class.isAssignableFrom(c)) { continue; } if (Modifier.isAbstract(c.getModifiers())) { continue; } // now instantiate and initialize it driverClasses.add(c.newInstance()); } catch (Throwable t) { } } info("scan complete in " + (System.currentTimeMillis() - start) + "ms"); return (Driver[]) driverClasses.toArray(new Driver[0]); }
From source file:org.apache.openjpa.meta.ClassMetaData.java
/** * Return true if this class has a concrete persistent superclass. *///from w ww . j a va2 s. c o m private boolean hasConcretePCSuperclass() { if (_super == null) return false; if (!Modifier.isAbstract(_super.getModifiers()) && (!getPCSuperclassMetaData().isAbstract())) return true; return getPCSuperclassMetaData().hasConcretePCSuperclass(); }
From source file:org.apache.hive.beeline.BeeLine.java
private Driver[] scanDriversOLD(String line) { long start = System.currentTimeMillis(); Set<String> paths = new HashSet<String>(); Set driverClasses = new HashSet(); for (StringTokenizer tok = new StringTokenizer(System.getProperty("java.ext.dirs"), System.getProperty("path.separator")); tok.hasMoreTokens();) { File[] files = new File(tok.nextToken()).listFiles(); for (int i = 0; files != null && i < files.length; i++) { paths.add(files[i].getAbsolutePath()); }//from w ww . j av a2s.c o m } for (StringTokenizer tok = new StringTokenizer(System.getProperty("java.class.path"), System.getProperty("path.separator")); tok.hasMoreTokens();) { paths.add(new File(tok.nextToken()).getAbsolutePath()); } for (Iterator<String> i = paths.iterator(); i.hasNext();) { File f = new File(i.next()); output(getColorBuffer().pad(loc("scanning", f.getAbsolutePath()), 60), false); try (ZipFile zf = new ZipFile(f)) { int total = zf.size(); int index = 0; for (Enumeration zfEnum = zf.entries(); zfEnum.hasMoreElements();) { ZipEntry entry = (ZipEntry) zfEnum.nextElement(); String name = entry.getName(); progress(index++, total); if (name.endsWith(".class")) { name = name.replace('/', '.'); name = name.substring(0, name.length() - 6); try { // check for the string "driver" in the class // to see if we should load it. Not perfect, but // it is far too slow otherwise. if (name.toLowerCase().indexOf("driver") != -1) { Class c = Class.forName(name, false, getClass().getClassLoader()); if (Driver.class.isAssignableFrom(c) && !(Modifier.isAbstract(c.getModifiers()))) { try { // load and initialize Class.forName(name); } catch (Exception e) { } driverClasses.add(c.newInstance()); } } } catch (Throwable t) { } } } progress(total, total); } catch (Exception e) { } } info("scan complete in " + (System.currentTimeMillis() - start) + "ms"); return (Driver[]) driverClasses.toArray(new Driver[0]); }
From source file:org.apache.openjpa.meta.ClassMetaData.java
/** * Ensure that the user has overridden the equals and hashCode methods, * and has the proper constructors.//w w w. j a v a2 s. c o m */ private void validateAppIdClassMethods(Class<?> oid) { try { oid.getConstructor((Class[]) null); } catch (Exception e) { throw new MetaDataException(_loc.get("null-cons", oid, _type)).setCause(e); } // check for equals and hashcode overrides; don't enforce it // for abstract application id classes, since they may not necessarily // declare primary key fields Method method; try { method = oid.getMethod("equals", new Class[] { Object.class }); } catch (Exception e) { throw new GeneralException(e).setFatal(true); } boolean abs = Modifier.isAbstract(_type.getModifiers()); if (!abs && method.getDeclaringClass() == Object.class) throw new MetaDataException(_loc.get("eq-method", _type)); try { method = oid.getMethod("hashCode", (Class[]) null); } catch (Exception e) { throw new GeneralException(e).setFatal(true); } if (!abs && method.getDeclaringClass() == Object.class) throw new MetaDataException(_loc.get("hc-method", _type)); }
From source file:org.apache.openjpa.meta.ClassMetaData.java
/** * Validate that the primary key class has all pk fields. *///from w w w .java 2 s. c om private void validateAppIdClassPKs(ClassMetaData meta, FieldMetaData[] fmds, Class<?> oid) { if (fmds.length == 0 && !Modifier.isAbstract(meta.getDescribedType().getModifiers())) throw new MetaDataException(_loc.get("no-pk", _type)); // check that the oid type contains all pk fields Field f; Method m; Class<?> c; for (int i = 0; i < fmds.length; i++) { switch (fmds[i].getDeclaredTypeCode()) { case JavaTypes.ARRAY: c = fmds[i].getDeclaredType().getComponentType(); if (c == byte.class || c == Byte.class || c == char.class || c == Character.class) { c = fmds[i].getDeclaredType(); break; } // else no break case JavaTypes.PC_UNTYPED: case JavaTypes.COLLECTION: case JavaTypes.MAP: case JavaTypes.OID: // we're validating embedded fields throw new MetaDataException(_loc.get("bad-pk-type", fmds[i])); default: c = fmds[i].getObjectIdFieldType(); } if (AccessCode.isField(fmds[i].getAccessType())) { f = Reflection.findField(oid, fmds[i].getName(), false); if (f == null || !f.getType().isAssignableFrom(c)) throw new MetaDataException(_loc.get("invalid-id", _type, fmds[i].getName())); } else if (AccessCode.isProperty(fmds[i].getAccessType())) { m = Reflection.findGetter(oid, fmds[i].getName(), false); if (m == null || !m.getReturnType().isAssignableFrom(c)) throw new MetaDataException(_loc.get("invalid-id", _type, fmds[i].getName())); m = Reflection.findSetter(oid, fmds[i].getName(), fmds[i].getObjectIdFieldType(), false); if (m == null || m.getReturnType() != void.class) throw new MetaDataException(_loc.get("invalid-id", _type, fmds[i].getName())); } } }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates and returns source code for persisting the remaining state not * done by {@link #generatePersistObjectMethod(Class, List, Map, Set, int)}. * This is for classes to allow properties that are not defined in a * sub-class to be persisted.//w ww .j av a2s .c o m * <p> * In the future we may want to have the parent classes persist properties * first and children to persist properties later. We can pool the property * changes in {@link PersistedSPOProperty} objects and persist them at the * end of the method call. * * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param accessors * The {@link Map} of accessor method names to their property * types which should be persisted into an {@link SPPersister} by * a workspace persister {@link SPListener}. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. * @param tabs * The number of tab characters to use to indent this generated * method block. * @return The source code for the generated persistObject method. */ private String generatePersistObjectMethodHelper(Class<? extends SPObject> visitedClass, Map<String, Class<?>> accessors, Map<String, Class<?>> mutators, Set<String> propertiesToPersistOnlyIfNonNull, int tabs) { StringBuilder sb = new StringBuilder(); final String genericObjectField = "o"; final String objectField = "castedObject"; final String persisterField = "persister"; final String converterField = "converter"; final String uuidField = "uuid"; final String exceptionField = "e"; //These are the properties on the sub-class helper calling this abstract //helper that have already been persisted by the current persistObject //call. These properties do not have to be persisted again. final String preProcessedPropField = "preProcessedProps"; final String staticPreProcessedPropField = "staticPreProcessedProps"; // persistObject method header. // public void persistObjectProperties( // SPObject o, // SPPersister persister, // SessionPersisterSuperConverter converter, // List<String> staticPreProcessedProps) // throws SPPersistenceException { println(sb, tabs, String.format("public void %s(%s %s, %s %s, %s %s, %s<%s> %s) throws %s {", PERSIST_OBJECT_PROPERTIES_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField, SPPersister.class.getSimpleName(), persisterField, SessionPersisterSuperConverter.class.getSimpleName(), converterField, List.class.getSimpleName(), String.class.getSimpleName(), staticPreProcessedPropField, SPPersistenceException.class.getSimpleName())); tabs++; // final List<String> preProcessedProperties = new ArrayList<String>(staticPreProcessedProps); println(sb, tabs, String.format("final %s<%s> %s = new %s<%s>(%s);", List.class.getSimpleName(), String.class.getSimpleName(), preProcessedPropField, ArrayList.class.getSimpleName(), String.class.getSimpleName(), staticPreProcessedPropField)); if (!accessors.isEmpty()) { boolean lastEntryInIfBlock = false; boolean variablesInitialized = false; Set<String> getterPropertyNames = new HashSet<String>(); for (Entry<String, Class<?>> e : mutators.entrySet()) { getterPropertyNames.add(SPAnnotationProcessorUtils.convertMethodToProperty(e.getKey())); } // Persist all of its persistable properties. for (Entry<String, Class<?>> e : accessors.entrySet()) { String propertyName = SPAnnotationProcessorUtils.convertMethodToProperty(e.getKey()); if (!getterPropertyNames.contains(propertyName)) continue; if (!variablesInitialized) { // final String uuid = o.getUUID(); println(sb, tabs, String.format("final %s %s = %s.%s();\n", String.class.getSimpleName(), uuidField, genericObjectField, GET_UUID_METHOD_NAME)); // If the SPObject class this persister helper handles is abstract, // use the type generic defined in the class header. // Otherwise, use the SPObject class directly. if (Modifier.isAbstract(visitedClass.getModifiers())) { // T castedObject = (T) o; println(sb, tabs, String.format("%s %s = (%s) %s;", TYPE_GENERIC_PARAMETER, objectField, TYPE_GENERIC_PARAMETER, genericObjectField)); } else { // <visitedClass> castedObject = (<visitedClass>) o; println(sb, tabs, String.format("%s %s = (%s) %s;", visitedClass.getSimpleName(), objectField, visitedClass.getSimpleName(), genericObjectField)); } // try { println(sb, tabs, "try {"); tabs++; variablesInitialized = true; } // Persist the property only if it has not been persisted yet // and (if required) persist if the value is not null. // // if (preProcessedProperties.contains("<property>")) { println(sb, tabs, String.format("if (!%s.contains(\"%s\")) {", preProcessedPropField, propertyName)); tabs++; boolean persistOnlyIfNonNull = propertiesToPersistOnlyIfNonNull.contains(propertyName); String propertyField = objectField + "." + e.getKey() + "()"; if (lastEntryInIfBlock) { niprintln(sb, ""); } if (persistOnlyIfNonNull) { // <getter type> <property> = castedObject.<getter>(); println(sb, tabs, String.format("%s %s = %s.%s();", e.getValue().getSimpleName(), propertyName, propertyField)); propertyField = propertyName; // if (castedObject.<getter>() != null) { println(sb, tabs, String.format("if (%s != null) {", propertyField)); tabs++; } final String dataTypeField = "dataType"; // DataType dataType; println(sb, tabs, String.format("%s %s;", DataType.class.getSimpleName(), dataTypeField)); String getPersistedProperty = objectField + "." + e.getKey() + "()"; if (e.getValue() == Object.class) { // if (castedObject.<getter>() == null) { println(sb, tabs, String.format("if (%s == null) {", getPersistedProperty)); tabs++; // dataType = PersisterUtils.getDataType(null); println(sb, tabs, String.format("%s = %s.getDataType(null);", dataTypeField, PersisterUtils.class.getSimpleName())); tabs--; println(sb, tabs, "} else {"); tabs++; // dataType = PersisterUtils.getDataType(castedObject.<getter>().getClass()); println(sb, tabs, String.format("%s = %s.getDataType(%s.getClass());", dataTypeField, PersisterUtils.class.getSimpleName(), getPersistedProperty)); tabs--; println(sb, tabs, "}"); importedClassNames.add(PersisterUtils.class.getName()); } else { // dataType = DataType.<type>; println(sb, tabs, String.format("%s = %s.%s;", dataTypeField, DataType.class.getSimpleName(), PersisterUtils.getDataType(e.getValue()).name())); } // persister.persistProperty(uuid, "<property>", dataType, converter.convertToBasicType(castedObject.<getter>())); println(sb, tabs, String.format("%s.%s(%s, \"%s\", %s, %s.%s(%s));", persisterField, PERSIST_PROPERTY_METHOD_NAME, uuidField, propertyName, dataTypeField, converterField, CONVERT_TO_BASIC_TYPE_METHOD_NAME, getPersistedProperty)); // preProcessedProperties.add("<property>"); println(sb, tabs, String.format("%s.add(\"%s\");", preProcessedPropField, propertyName)); importedClassNames.add(DataType.class.getName()); if (persistOnlyIfNonNull) { tabs--; println(sb, tabs, "}"); lastEntryInIfBlock = true; } else { lastEntryInIfBlock = false; } tabs--; println(sb, tabs, "}"); } if (variablesInitialized) { tabs--; // } catch (Exception e) { println(sb, tabs, String.format("} catch (%s %s) {", Exception.class.getSimpleName(), exceptionField)); tabs++; // throw new SPPersistenceException(uuid, e); println(sb, tabs, String.format("throw new %s(%s, %s);", SPPersistenceException.class.getSimpleName(), uuidField, exceptionField)); tabs--; println(sb, tabs, "}"); } } if (SPObject.class.isAssignableFrom(visitedClass.getSuperclass())) { Class<?> superclass = visitedClass.getSuperclass(); // super.persistObjectProperties(o, persister, converter, preProcessedProperties); println(sb, tabs, String.format("super.%s(%s, %s, %s, %s);", PERSIST_OBJECT_PROPERTIES_METHOD_NAME, genericObjectField, persisterField, converterField, preProcessedPropField)); } tabs--; println(sb, tabs, "}"); return sb.toString(); }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
@SuppressWarnings("unchecked") protected <OUT, IN1, IN2> TypeInformation<OUT> analyzePojo(Class<OUT> clazz, ArrayList<Type> typeHierarchy, ParameterizedType parameterizedType, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { if (!Modifier.isPublic(clazz.getModifiers())) { LOG.info("Class " + clazz.getName() + " is not public, cannot treat it as a POJO type. Will be handled as GenericType"); return new GenericTypeInfo<OUT>(clazz); }//from w w w.j av a 2s . c o m // add the hierarchy of the POJO itself if it is generic if (parameterizedType != null) { getTypeHierarchy(typeHierarchy, parameterizedType, Object.class); } // create a type hierarchy, if the incoming only contains the most bottom one or none. else if (typeHierarchy.size() <= 1) { getTypeHierarchy(typeHierarchy, clazz, Object.class); } List<Field> fields = getAllDeclaredFields(clazz, false); if (fields.size() == 0) { LOG.info("No fields detected for " + clazz + ". Cannot be used as a PojoType. Will be handled as GenericType"); return new GenericTypeInfo<OUT>(clazz); } List<PojoField> pojoFields = new ArrayList<PojoField>(); for (Field field : fields) { Type fieldType = field.getGenericType(); if (!isValidPojoField(field, clazz, typeHierarchy)) { LOG.info(clazz + " is not a valid POJO type"); return null; } try { ArrayList<Type> fieldTypeHierarchy = new ArrayList<Type>(typeHierarchy); fieldTypeHierarchy.add(fieldType); TypeInformation<?> ti = createTypeInfoWithTypeHierarchy(fieldTypeHierarchy, fieldType, in1Type, in2Type); pojoFields.add(new PojoField(field, ti)); } catch (InvalidTypesException e) { Class<?> genericClass = Object.class; if (isClassType(fieldType)) { genericClass = typeToClass(fieldType); } pojoFields.add(new PojoField(field, new GenericTypeInfo<OUT>((Class<OUT>) genericClass))); } } CompositeType<OUT> pojoType = new PojoTypeInfo<OUT>(clazz, pojoFields); // // Validate the correctness of the pojo. // returning "null" will result create a generic type information. // List<Method> methods = getAllDeclaredMethods(clazz); for (Method method : methods) { if (method.getName().equals("readObject") || method.getName().equals("writeObject")) { LOG.info(clazz + " contains custom serialization methods we do not call."); return null; } } // Try retrieving the default constructor, if it does not have one // we cannot use this because the serializer uses it. Constructor defaultConstructor = null; try { defaultConstructor = clazz.getDeclaredConstructor(); } catch (NoSuchMethodException e) { if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { LOG.info(clazz + " is abstract or an interface, having a concrete " + "type can increase performance."); } else { LOG.info(clazz + " must have a default constructor to be used as a POJO."); return null; } } if (defaultConstructor != null && !Modifier.isPublic(defaultConstructor.getModifiers())) { LOG.info("The default constructor of " + clazz + " should be Public to be used as a POJO."); return null; } // everything is checked, we return the pojo return pojoType; }
From source file:org.apache.openjpa.kernel.BrokerImpl.java
public Object newInstance(Class cls) { assertOpen();/*w w w . j av a2 s.com*/ if (!cls.isInterface() && Modifier.isAbstract(cls.getModifiers())) throw new UnsupportedOperationException(_loc.get("new-abstract", cls).getMessage()); // 1.5 doesn't initialize classes without a true Class.forName if (!PCRegistry.isRegistered(cls)) { try { Class.forName(cls.getName(), true, AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls))); } catch (Throwable t) { } } if (_repo.getMetaData(cls, getClassLoader(), false) == null) throw new IllegalArgumentException(_loc.get("no-interface-metadata", cls.getName()).getMessage()); try { return PCRegistry.newInstance(cls, null, false); } catch (IllegalStateException ise) { IllegalArgumentException iae = new IllegalArgumentException(ise.getMessage()); iae.setStackTrace(ise.getStackTrace()); throw iae; } }