List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:com.grepcurl.random.ObjectGenerator.java
@SuppressWarnings("unused") public <T> T generate(Class<T> klass, Object... constructorArgs) { Validate.notNull(klass);/*from ww w . ja v a2 s. com*/ Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s", klass, Arrays.toString(constructorArgs))); } try { Deque<Object> objectStack = new ArrayDeque<>(); Class[] constructorTypes = _toClasses(constructorArgs); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, new SetterOverrides(), t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { throw new FailedRandomObjectGenerationException(e); } }
From source file:org.livespark.formmodeler.renderer.backend.service.impl.Model2FormTransformerServiceImpl.java
protected Set<FieldSetting> getClassFieldSettings(Class clazz) { TreeSet<FieldSetting> settings = new TreeSet<FieldSetting>(); for (Field field : clazz.getDeclaredFields()) { for (Annotation annotation : field.getAnnotations()) { if (annotation instanceof FieldDef) { FieldDef fieldDef = (FieldDef) annotation; Class fieldType = getFieldType(field, fieldDef); Class realType = fieldType; if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); Type paramArg = parameterizedType.getActualTypeArguments()[0]; realType = (Class) paramArg; }/*from ww w . j a va 2 s.c om*/ FieldSetting setting = new FieldSetting( field.getName(), new DefaultFieldTypeInfo(realType.getName(), fieldType.isAssignableFrom(List.class), fieldType.isEnum()), realType, fieldDef, field.getAnnotations()); settings.add(setting); } } } if (clazz.getSuperclass() != null) { settings.addAll(getClassFieldSettings(clazz.getSuperclass())); } return settings; }
From source file:com.evolveum.midpoint.repo.sql.query.restriction.ItemRestriction.java
/** * This method provides transformation from {@link String} value defined in * {@link com.evolveum.midpoint.repo.sql.query.definition.VirtualQueryParam#value()} to real object. Currently only * to simple types and enum values./*from ww w . j a v a 2 s . c om*/ * * @param param * @param propPath * @return real value * @throws QueryException */ private Object createQueryParamValue(VirtualQueryParam param, ItemPath propPath) throws QueryException { Class type = param.type(); String value = param.value(); try { if (type.isPrimitive()) { return type.getMethod("valueOf", new Class[] { String.class }).invoke(null, new Object[] { value }); } if (type.isEnum()) { return Enum.valueOf(type, value); } } catch (Exception ex) { throw new QueryException("Couldn't transform virtual query parameter '" + param.name() + "' from String to '" + type + "', reason: " + ex.getMessage(), ex); } throw new QueryException("Couldn't transform virtual query parameter '" + param.name() + "' from String to '" + type + "', it's not yet implemented."); }
From source file:com.discovery.darchrow.lang.ClassUtil.java
/** * class info map for LOGGER./* ww w .j av a 2 s.c o m*/ * * @param klass * the clz * @return the map for log */ public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) { if (Validator.isNullOrEmpty(klass)) { return null; } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.feilong.core.date.DatePattern" map.put("clz.getName()", klass.getName());//"com.feilong.core.date.DatePattern" map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern" map.put("clz.getComponentType()", klass.getComponentType()); // ?? voidboolean?byte?char?short?int?long?float double? map.put("clz.isPrimitive()", klass.isPrimitive()); // ??, map.put("clz.isLocalClass()", klass.isLocalClass()); // ????,?????? map.put("clz.isMemberClass()", klass.isMemberClass()); //isSynthetic()?Class????java??false?trueJVM???java?????? map.put("clz.isSynthetic()", klass.isSynthetic()); map.put("clz.isArray()", klass.isArray()); map.put("clz.isAnnotation()", klass.isAnnotation()); //??true map.put("clz.isAnonymousClass()", klass.isAnonymousClass()); map.put("clz.isEnum()", klass.isEnum()); return map; }
From source file:com.bstek.dorado.data.type.manager.DefaultDataTypeManager.java
/** * Class?DataType// w ww .j a v a2 s . c o m */ private Set<DataTypeWrapper> findAllMatchingDataTypes(Class<?> type) { Set<DataTypeWrapper> dtws = new HashSet<DataTypeWrapper>(); DataTypeDefinition dataType = getDefinedDataTypeDefinition(type); if (dataType != null) { dtws.add(new DataTypeWrapper(dataType, type)); } // ?? dtws.addAll(findMatchingDataTypeForInterface(type)); // ? for (Class<?> tempType = type.getSuperclass(); tempType != null; tempType = tempType.getSuperclass()) { // ?? dtws.addAll(findMatchingDataTypeForInterface(tempType)); if (type.isEnum() && tempType.equals(Object.class)) { tempType = String.class; } dataType = getDefinedDataTypeDefinition(tempType); if (dataType != null) { dtws.add(new DataTypeWrapper(dataType, tempType)); break; } } return dtws; }
From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java
/** * Method to populate a simple (ie non collection) type which can be a java built-in type or a user's custom type. * * @param result The result object on which the generated value will be set * @param field The field in which the generated value will be set * @param context The context of this call * @throws IllegalAccessException Thrown when the generated value cannot be set to the given field * @throws NoSuchMethodException Thrown when there is no setter for the given field * @throws InvocationTargetException Thrown when the setter of the given field can not be invoked */// w ww . ja v a 2 s. c om private void populateField(Object result, final Field field, PopulatorContext context) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class<?> fieldType = field.getType(); Class<?> resultClass = result.getClass(); try { context.pushStackItem(new ContextStackItem(result, field)); Object object = null; Randomizer<?> randomizer = getRandomizer(resultClass, field); if (randomizer != null) { // A randomizer was found, so use this one. object = randomizer.getRandomValue(); } else { // No randomizer was found. if (fieldType.isEnum()) { // This is a enum, so use the enumRandomizer. object = enumRandomizer.<Enum>getRandomEnumValue((Class<Enum>) fieldType); } else if (isCollectionType(fieldType)) { // This is a collection, so use getRandomCollection method. object = getRandomCollection(field); } else { // Consider the class as a child bean. object = populateBeanImpl(fieldType, context); } } setProperty(result, field, object); } catch (RandomizerSkipException e) { LOGGER.log(Level.FINE, String.format("Randomizer has skipped property %s", field)); } finally { context.popStackItem(); } }
From source file:com.delcyon.capo.Configuration.java
@SuppressWarnings({ "unchecked", "static-access" }) public Configuration(String... programArgs) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); options = new Options(); // the enum this is a little complicated, but it gives us a nice // centralized place to put all of the system parameters // and lets us iterate of the list of options and preferences PREFERENCE[] preferences = PREFERENCE.values(); for (PREFERENCE preference : preferences) { // not the most elegant, but there is no default constructor, but // the has arguments value is always there OptionBuilder optionBuilder = OptionBuilder.hasArg(preference.hasArgument); if (preference.hasArgument == true) { String[] argNames = preference.arguments; for (String argName : argNames) { optionBuilder = optionBuilder.withArgName(argName); }/* www .ja v a2 s .c o m*/ } optionBuilder = optionBuilder.withDescription(preference.getDescription()); optionBuilder = optionBuilder.withLongOpt(preference.getLongOption()); options.addOption(optionBuilder.create(preference.getOption())); preferenceHashMap.put(preference.toString(), preference); } //add dynamic options Set<String> preferenceProvidersSet = CapoApplication.getAnnotationMap() .get(PreferenceProvider.class.getCanonicalName()); if (preferenceProvidersSet != null) { for (String className : preferenceProvidersSet) { Class preferenceClass = Class.forName(className).getAnnotation(PreferenceProvider.class) .preferences(); if (preferenceClass.isEnum()) { Object[] enumObjects = preferenceClass.getEnumConstants(); for (Object enumObject : enumObjects) { Preference preference = (Preference) enumObject; //filter out any preferences that don't belong on this server or client. if (preference.getLocation() != Location.BOTH) { if (CapoApplication.isServer() == true && preference.getLocation() == Location.CLIENT) { continue; } else if (CapoApplication.isServer() == false && preference.getLocation() == Location.SERVER) { continue; } } preferenceHashMap.put(preference.toString(), preference); boolean hasArgument = false; if (preference.getArguments() == null || preference.getArguments().length == 0) { hasArgument = false; } else { hasArgument = true; } OptionBuilder optionBuilder = OptionBuilder.hasArg(hasArgument); if (hasArgument == true) { String[] argNames = preference.getArguments(); for (String argName : argNames) { optionBuilder = optionBuilder.withArgName(argName); } } optionBuilder = optionBuilder.withDescription(preference.getDescription()); optionBuilder = optionBuilder.withLongOpt(preference.getLongOption()); options.addOption(optionBuilder.create(preference.getOption())); } } } } // create parser CommandLineParser commandLineParser = new GnuParser(); this.commandLine = commandLineParser.parse(options, programArgs); Preferences systemPreferences = Preferences .systemNodeForPackage(CapoApplication.getApplication().getClass()); String capoDirString = null; while (true) { capoDirString = systemPreferences.get(PREFERENCE.CAPO_DIR.longOption, null); if (capoDirString == null) { systemPreferences.put(PREFERENCE.CAPO_DIR.longOption, PREFERENCE.CAPO_DIR.defaultValue); capoDirString = PREFERENCE.CAPO_DIR.defaultValue; try { systemPreferences.sync(); } catch (BackingStoreException e) { //e.printStackTrace(); if (systemPreferences.isUserNode() == false) { System.err.println("Problem with System preferences, trying user's"); systemPreferences = Preferences .userNodeForPackage(CapoApplication.getApplication().getClass()); continue; } else //just bail out { throw e; } } } break; } disableAutoSync = hasOption(PREFERENCE.DISABLE_CONFIG_AUTOSYNC); File capoDirFile = new File(capoDirString); if (capoDirFile.exists() == false) { if (disableAutoSync == false) { capoDirFile.mkdirs(); } } File configDir = new File(capoDirFile, PREFERENCE.CONFIG_DIR.defaultValue); if (configDir.exists() == false) { if (disableAutoSync == false) { configDir.mkdirs(); } } if (disableAutoSync == false) { capoConfigFile = new File(configDir, CONFIG_FILENAME); if (capoConfigFile.exists() == false) { Document configDocument = CapoApplication.getDefaultDocument("config.xml"); FileOutputStream configFileOutputStream = new FileOutputStream(capoConfigFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(configDocument), new StreamResult(configFileOutputStream)); configFileOutputStream.close(); } configDocument = documentBuilder.parse(capoConfigFile); } else //going memory only, because of disabled auto sync { configDocument = CapoApplication.getDefaultDocument("config.xml"); } if (configDocument instanceof CDocument) { ((CDocument) configDocument).setSilenceEvents(true); } loadPreferences(); preferenceValueHashMap.put(PREFERENCE.CAPO_DIR.longOption, capoDirString); //print out preferences //this also has the effect of persisting all of the default values if a values doesn't already exist for (PREFERENCE preference : preferences) { if (getValue(preference) != null) { CapoApplication.logger.log(Level.CONFIG, preference.longOption + "='" + getValue(preference) + "'"); } } CapoApplication.logger.setLevel(Level.parse(getValue(PREFERENCE.LOGGING_LEVEL))); }
From source file:com.grepcurl.random.ObjectGenerator.java
protected <T> T generate(Class<T> klass, SetterOverrides setterOverrides, Deque<Object> objectStack, Object... constructorArgs) { Validate.notNull(klass);//from w w w . jav a 2 s . c om Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s, with overrides: %s", klass, Arrays.toString(constructorArgs), setterOverrides)); } try { Class[] constructorTypes = _toClasses(constructorArgs); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, setterOverrides, t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { e.printStackTrace(); throw new FailedRandomObjectGenerationException(e); } }
From source file:org.bimserver.tools.generators.ProtocolBuffersGenerator.java
private String getDefaultLiteralCode(Class<?> type) { if (type == Boolean.class || type == boolean.class) { return "false"; } else if (type == Integer.class || type == int.class) { return "0"; } else if (type == Long.class || type == long.class) { return "0L"; } else if (type.isEnum()) { return "null"; } else {//from ww w. j a va 2s. c o m return "null"; } }
From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java
public CustomHeader decodeCustomHeader(Class<? extends CustomHeader> classHeader) throws RpcCommandException { CustomHeader objectHeader;// ww w. ja v a 2 s . c o m try { objectHeader = classHeader.newInstance(); } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } if (MapUtils.isNotEmpty(this.customFields)) { Field[] fields = getClazzFields(classHeader); for (Field field : fields) { String fieldName = field.getName(); Class clazz = field.getType(); if (Modifier.isStatic(field.getModifiers()) || fieldName.startsWith("this")) { continue; } String value = this.customFields.get(fieldName); if (value == null) { continue; } field.setAccessible(true); Object valueParsed; if (clazz.isEnum()) { valueParsed = Enum.valueOf(clazz, value); } else { String type = getCanonicalName(clazz); try { valueParsed = ClassUtils.parseSimpleValue(type, value); } catch (ParseException e) { throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName + "> type <" + getCanonicalName(clazz) + "> parse error:" + e.getMessage()); } } if (valueParsed == null) { throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName + "> type <" + getCanonicalName(clazz) + "> is not supported."); } try { field.set(objectHeader, valueParsed); } catch (IllegalAccessException e) { throw new RpcCommandException( "Encode the header failed, set the value of field < " + fieldName + "> error.", e); } } objectHeader.checkFields(); } return objectHeader; }