List of usage examples for java.lang Class getFields
@CallerSensitive public Field[] getFields() throws SecurityException
From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java
/** * ?//w w w . j av a 2 s . c om * @param sourceClass * @param isGetDeclaredField ???Declared * @param isFromSuperClassGet ??? * @param isDESCGet ??????????? * @return */ private static List<Field> getFields(Class<?> sourceClass, boolean isGetDeclaredField, boolean isFromSuperClassGet, boolean isDESCGet) { List<Field> fieldList = new ArrayList<Field>(); //?? if (isFromSuperClassGet) { //?? List<Class<?>> classList = getSuperClasses(sourceClass, true); //??? if (isDESCGet) { for (int w = classList.size() - 1; w > -1; w--) { for (Field field : isGetDeclaredField ? classList.get(w).getDeclaredFields() : classList.get(w).getFields()) { fieldList.add(field); } } } else { for (int w = 0; w < classList.size(); w++) { for (Field field : isGetDeclaredField ? classList.get(w).getDeclaredFields() : classList.get(w).getFields()) { fieldList.add(field); } } } } else { for (Field field : isGetDeclaredField ? sourceClass.getDeclaredFields() : sourceClass.getFields()) { fieldList.add(field); } } return fieldList; }
From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java
/** * Returns the name of the fields that are enum constants according to reflection * * @return a non-null set of fields that are enum constants *//* ww w. java2 s . co m*/ private Set<String> enumConstantsNames(final Class enumClass) { final Set<String> enumConstantFieldNames = new HashSet<String>(); for (final Field field : enumClass.getFields()) { if (field.isEnumConstant()) enumConstantFieldNames.add(field.getName()); } return enumConstantFieldNames; }
From source file:com.fluidops.iwb.api.ProviderServiceImpl.java
@Override public MetaData getMetaData() throws Exception { MetaData md = new MetaData(); for (String s : EndpointImpl.api().getProviderService().getProviderClasses()) { Class c = DynamicScriptingSupport.loadClass(s); AbstractFlexProvider p = (AbstractFlexProvider) c.newInstance(); Class config = p.getConfigClass(); MethodMetaData mmd = new MethodMetaData(); md.methods.add(mmd);// w w w . ja v a 2 s . c o m mmd.name = c.getSimpleName(); if (c.getAnnotation(TypeConfigDoc.class) != null) mmd.doc = ((TypeConfigDoc) c.getAnnotation(TypeConfigDoc.class)).value(); mmd.returnType = String.class; for (Field f : config.getFields()) { ParamMetaData mp = new ParamMetaData(); mmd.params.add(mp); mp.param = new Param(f.getName(), f.getType().getCanonicalName(), null, false, f.getAnnotation(TypeConfigDoc.class) == null ? null : f.getAnnotation(TypeConfigDoc.class).value()); mp.param.setAnnotated(true); mp.type = f.getType(); mp.listType = f.getAnnotation(ParameterConfigDoc.class) == null ? null : f.getAnnotation(ParameterConfigDoc.class).listType(); } } return md; }
From source file:org.red5.io.amf.Output.java
/** * Writes an arbitrary object to the output. * * @param serializer Output writer//from w w w . j a va 2s . c o m * @param object Object to write */ protected void writeArbitraryObject(Object object, Serializer serializer) { if (log.isDebugEnabled()) { log.debug("writeObject"); } // If we need to serialize class information... Class<?> objectClass = object.getClass(); if (!objectClass.isAnnotationPresent(Anonymous.class)) { // Write out start object marker for class name buf.put(AMF.TYPE_CLASS_OBJECT); putString(buf, objectClass.getName()); } else { // Write out start object marker without class name buf.put(AMF.TYPE_OBJECT); } // Get public field values Map<String, Object> values = new HashMap<String, Object>(); // Iterate thru fields of an object to build "name-value" map from it for (Field field : objectClass.getFields()) { if (field.isAnnotationPresent(DontSerialize.class)) { if (log.isDebugEnabled()) { log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize"); } continue; } else { int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) { log.warn("Using \"transient\" to declare fields not to be serialized is " + "deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead."); continue; } } Object value; try { // Get field value value = field.get(object); } catch (IllegalAccessException err) { // Swallow on private and protected properties access exception continue; } // Put field to the map of "name-value" pairs values.put(field.getName(), value); } // Output public values Iterator<Map.Entry<String, Object>> it = values.entrySet().iterator(); // Iterate thru map and write out properties with separators while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); // Write out prop name putString(buf, entry.getKey()); // Write out serializer.serialize(this, entry.getValue()); } // Write out end of object marker buf.put((byte) 0x00); buf.put((byte) 0x00); buf.put(AMF.TYPE_END_OF_OBJECT); }
From source file:com.benchmark.TikaCLI.java
private void displayMetModels() { Class<?>[] modelClasses = Metadata.class.getInterfaces(); Arrays.sort(modelClasses, new Comparator<Class<?>>() { public int compare(Class<?> o1, Class<?> o2) { return o1.getName().compareTo(o2.getName()); }/*from w w w.j a va 2s . c o m*/ }); for (Class<?> modelClass : modelClasses) { // we don't care about internal Tika met classes // if we do, then we can take this conditional out if (!modelClass.getSimpleName().contains("Tika")) { System.out.println(modelClass.getSimpleName()); Field[] keyFields = modelClass.getFields(); Arrays.sort(keyFields, new Comparator<Field>() { public int compare(Field o1, Field o2) { return o1.getName().compareTo(o2.getName()); } }); for (Field keyField : keyFields) { System.out.println(" " + keyField.getName()); } } } }
From source file:org.rhq.enterprise.gui.legacy.taglib.ConstantsTag.java
public int doEndTag() throws JspException { try {//from w w w . ja v a 2 s . c o m JspWriter out = pageContext.getOut(); if (className == null) { className = pageContext.getServletContext().getInitParameter(constantsClassNameParam); } if (validate(out)) { // we're misconfigured. getting this far // is a matter of what our failure mode is; // if we haven't thrown an Error, carry on log.debug("constants tag misconfigured"); return EVAL_PAGE; } Map<String, String> fieldMap; if (constants.containsKey(className)) { // we cache the result of the constant's class // reflection field walk as a map fieldMap = (Map<String, String>) constants.get(className); } else { fieldMap = new HashMap<String, String>(); Class typeClass = Class.forName(className); if (typeClass.isEnum()) { for (Object enumConstantObj : typeClass.getEnumConstants()) { Enum enumConstant = (Enum) enumConstantObj; // Set name *and* value to enum name (e.g. name of ResourceCategory.PLATFORM = "PLATFORM") // NOTE: We do not set the value to enumConstant.ordinal(), because there is no way to // convert the ordinal value back to an Enum (i.e. no Enum.valueOf(int ordinal) method). fieldMap.put(enumConstant.name(), enumConstant.name()); } } else { Object instance = typeClass.newInstance(); Field[] fields = typeClass.getFields(); for (Field field : fields) { // string comparisons of class names should be cheaper // than reflective Class comparisons, the asumption here // is that most constants are Strings, ints and booleans // but a minimal effort is made to accomadate all types // and represent them as String's for our tag's output String fieldType = field.getType().getName(); String strVal; if (fieldType.equals("java.lang.String")) { strVal = (String) field.get(instance); } else if (fieldType.equals("int")) { strVal = Integer.toString(field.getInt(instance)); } else if (fieldType.equals("boolean")) { strVal = Boolean.toString(field.getBoolean(instance)); } else if (fieldType.equals("char")) { strVal = Character.toString(field.getChar(instance)); } else if (fieldType.equals("double")) { strVal = Double.toString(field.getDouble(instance)); } else if (fieldType.equals("float")) { strVal = Float.toString(field.getFloat(instance)); } else if (fieldType.equals("long")) { strVal = Long.toString(field.getLong(instance)); } else if (fieldType.equals("short")) { strVal = Short.toString(field.getShort(instance)); } else if (fieldType.equals("byte")) { strVal = Byte.toString(field.getByte(instance)); } else { strVal = field.get(instance).toString(); } fieldMap.put(field.getName(), strVal); } } // cache the result constants.put(className, fieldMap); } if ((symbol != null) && !fieldMap.containsKey(symbol)) { // tell the developer that he's being a dummy and what // might be done to remedy the situation // TODO: what happens if the constants change? // do we need to throw a JspException, here? - mtk String err1 = symbol + " was not found in " + className + "\n"; String err2 = err1 + "use <constants:diag classname=\"" + className + "\"/>\n" + "to figure out what you're looking for"; log.error(err2); die(out, err1); } if (varSpecified) { doSet(fieldMap); } else { doOutput(fieldMap, out); } } catch (JspException e) { throw e; } catch (Exception e) { log.debug("doEndTag() failed: ", e); throw new JspException("Could not access constants tag", e); } return EVAL_PAGE; }
From source file:gov.va.vinci.leo.ae.LeoBaseAnnotator.java
/** * Returns parameters defined in a static class named Param with static ConfigurationParameter objects. * <p/>/*from ww w . j a v a 2s. c o m*/ * For Example: * <p/> * <pre> * {@code * protected String parameterName = "parameter value"; * * public static class Param { * public static ConfigurationParameter PARAMETER_NAME * = new ConfigurationParameterImpl( * "parameterName", "Description", "String", false, true, new String[] {} * ); * } * }</pre> * * @return the annotator parameters this annotator can accept. * @throws IllegalAccessException if there is an exception trying to get annotator parameters via reflection. */ protected ConfigurationParameter[] getAnnotatorParams() throws IllegalAccessException { ConfigurationParameter params[] = null; for (Class c : this.getClass().getDeclaredClasses()) { if (c.isEnum() && Arrays.asList(c.getInterfaces()).contains(ConfigurationParameter.class)) { params = new ConfigurationParameter[EnumSet.allOf(c).size()]; int counter = 0; for (Object o : EnumSet.allOf(c)) { params[counter] = ((ConfigurationParameter) o); counter++; } break; } else if (c.getCanonicalName().endsWith(".Param")) { Field[] fields = c.getFields(); List<ConfigurationParameter> paramList = new ArrayList<ConfigurationParameter>(); for (Field f : fields) { if (ConfigurationParameter.class.isAssignableFrom(f.getType())) { paramList.add((ConfigurationParameter) f.get(null)); } } params = paramList.toArray(new ConfigurationParameter[paramList.size()]); } } return params; }
From source file:org.mulesoft.restx.component.BaseComponent.java
protected void initialiseComponentDescriptor() throws RestxException { if (annotationsHaveBeenParsed || componentDescriptor != null) { return;//from w ww . jav a2 s . c o m } final Class<? extends BaseComponent> myclass = this.getClass(); /* * Examine the class annotations to get information about the component. */ final ComponentInfo ci = this.getClass().getAnnotation(ComponentInfo.class); if (ci == null) { throw new RestxException("Component does not have a ComponentInfo annotation"); } componentDescriptor = new ComponentDescriptor(ci.name(), ci.desc(), ci.doc()); /* * Examine field annotations to identify resource creation time parameters. */ for (final Field f : myclass.getFields()) { final Parameter fa = f.getAnnotation(Parameter.class); if (fa != null) { final String paramName = fa.name(); final String paramDesc = fa.desc(); String defaultVal = null; boolean required = true; String[] choices = null; // Check if we have a default value and set that one as well final Default fad = f.getAnnotation(Default.class); if (fad != null) { defaultVal = fad.value(); required = false; } // Check if we have a list of choices final Choices cad = f.getAnnotation(Choices.class); if (cad != null) { choices = cad.value(); } final Class<?> ftype = f.getType(); componentDescriptor.addParameter(paramName, createParamDefType(ftype, paramDesc, required, defaultVal, choices)); } } /* * Examine the method annotations to identify service methods and their * parameters. */ paramOrder = new HashMap<String, ArrayList<String>>(); paramTypes = new HashMap<String, ArrayList<Class<?>>>(); for (final Method m : myclass.getMethods()) { if (m.isAnnotationPresent(Service.class)) { final String serviceName = m.getName(); final Service at = m.getAnnotation(Service.class); boolean pinreq = false; if (m.isAnnotationPresent(ParamsInReqBody.class)) { pinreq = true; } // Looking for output type annotations ArrayList<String> outputTypes = null; if (m.isAnnotationPresent(OutputType.class)) { final OutputType ot = m.getAnnotation(OutputType.class); outputTypes = new ArrayList<String>(); outputTypes.add(ot.value()); } if (m.isAnnotationPresent(OutputTypes.class)) { final OutputTypes ots = m.getAnnotation(OutputTypes.class); final String[] otsSpecs = ots.value(); if (otsSpecs.length > 0) { if (outputTypes == null) { outputTypes = new ArrayList<String>(); } for (final String ts : otsSpecs) { outputTypes.add(ts); } } } // Looking for output type annotations ArrayList<String> inputTypes = null; if (m.isAnnotationPresent(InputType.class)) { final InputType it = m.getAnnotation(InputType.class); inputTypes = new ArrayList<String>(); final String it_val = it.value(); if (!it_val.equals(InputType.NO_INPUT)) { inputTypes.add(it_val); } else { inputTypes.add(null); } } if (m.isAnnotationPresent(InputTypes.class)) { final InputTypes its = m.getAnnotation(InputTypes.class); final String[] itsSpecs = its.value(); if (itsSpecs.length > 0) { if (inputTypes == null) { inputTypes = new ArrayList<String>(); } for (final String ts : itsSpecs) { if (!ts.equals(InputType.NO_INPUT)) { inputTypes.add(ts); } else { inputTypes.add(null); } } } } final ServiceDescriptor sd = new ServiceDescriptor(at.desc(), pinreq, outputTypes, inputTypes); final Class<?>[] types = m.getParameterTypes(); final Annotation[][] allParamAnnotations = m.getParameterAnnotations(); int i = 0; final ArrayList<String> positionalParams = new ArrayList<String>(); for (final Annotation[] pa : allParamAnnotations) { String name = null; String desc = null; boolean required = true; String defaultVal = null; for (final Annotation a : pa) { if (a.annotationType() == Parameter.class) { name = ((Parameter) a).name(); desc = ((Parameter) a).desc(); if (!paramOrder.containsKey(serviceName)) { paramOrder.put(serviceName, new ArrayList<String>()); paramTypes.put(serviceName, new ArrayList<Class<?>>()); } if (((Parameter) a).positional()) { positionalParams.add(name); } paramOrder.get(serviceName).add(name); paramTypes.get(serviceName).add(types[i]); } else if (a.annotationType() == Default.class) { defaultVal = ((Default) a).value(); required = false; } } if (name != null) { sd.addParameter(name, createParamDefType(types[i], desc, required, defaultVal, null)); } ++i; } if (!positionalParams.isEmpty()) { sd.setPositionalParameters(positionalParams); } componentDescriptor.addService(m.getName(), sd); } } annotationsHaveBeenParsed = true; }
From source file:org.jakz.common.JSONObject.java
/** * DO NOT USE! This is just a sketch in development. * @param source// w w w . j a v a 2 s .c om * @param target * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException */ public static Object injectIntoPOJO(Object source, Object target) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchMethodException, SecurityException, InvocationTargetException { if (source instanceof Byte || source instanceof Character || source instanceof Short || source instanceof Integer || source instanceof Long || source instanceof Boolean || source instanceof Float || source instanceof Double || source instanceof String || source instanceof BigInteger || source instanceof BigDecimal) { return source; } Class<?> pojoClass = null; if (target != null) pojoClass = target.getClass(); else { pojoClass = source.getClass(); target = pojoClass.newInstance(); } Field[] field = pojoClass.getFields(); Object toReturn = pojoClass.newInstance(); for (int i = 0; i < field.length; i++) { String fieldName = field[i].getName(); Class<?> fieldType = field[i].getType(); ParameterizedType fieldParameterizedType = (ParameterizedType) field[i].getGenericType(); if (source instanceof JSONObject) { JSONObject sjson = (JSONObject) source; if (fieldType == Integer.class || fieldType == Byte.class) field[i].set(target, sjson.getInt(fieldName)); else if (fieldType == BigInteger.class || fieldType == Long.class) field[i].set(target, sjson.getBigInteger(fieldName)); else if (fieldType == Boolean.class) field[i].set(target, sjson.getBoolean(fieldName)); else if (fieldType == Double.class) field[i].set(target, sjson.getDouble(fieldName)); else if (fieldType == String.class || fieldType == Character.class) field[i].set(target, sjson.getString(fieldName)); else if (fieldType.isArray()) { JSONArray ajson = sjson.getJSONArray(fieldName); Object apojo = Array.newInstance(fieldType, ajson.length()); Class<?> componentType = fieldType.getComponentType(); for (int ai = 0; ai < ajson.length(); ai++) { Object toAddValue = ajson.get(i); Object componentPOJO = componentType.newInstance(); Array.set(apojo, ai, injectIntoPOJO(toAddValue, componentPOJO)); } field[i].set(target, apojo); } else if (Collection.class.isAssignableFrom(fieldType)) { JSONArray ajson = sjson.getJSONArray(fieldName); Collection<?> cpojo = (Collection<?>) fieldType.newInstance(); for (int ai = 0; ai < ajson.length(); ai++) { Object toAddValue = ajson.get(i); Class<?> genericType = (Class<?>) fieldParameterizedType.getActualTypeArguments()[0]; System.out.println("generic type: " + genericType.getName()); Object componentPOJO = genericType.newInstance(); //TODO - funkar inte Method addMethod = fieldType.getMethod("add", Object.class); addMethod.invoke(cpojo, injectIntoPOJO(toAddValue, componentPOJO)); } field[i].set(target, cpojo); } else { try { Object pojoInstance = fieldType.newInstance(); field[i].set(target, injectIntoPOJO(sjson.get(fieldName), pojoInstance)); } catch (Exception e) { throw new JSONException("Could not inject field " + fieldName + " of type " + fieldType.getName() + " into POJO.", e); } } } //add more sources } return toReturn; }
From source file:de.cubeisland.engine.module.stats.StatsManager.java
/** * Register a statistic./*from w w w . ja v a 2s. c o m*/ * This will make this StatsManager handle the statistic's database connection * and register it as a listener. * * @param statType The stat class to register */ public void register(Class<? extends Stat> statType) { if (!this.started) { throw new IllegalStateException("StatsManager not started!"); } try { // Get the Constructor, and construct a new instance of the Stat. Constructor<? extends Stat> constructor = statType.getConstructor(); Stat stat = constructor.newInstance(); Method init = statType.getMethod("init", this.getClass(), Module.class); init.invoke(stat, this, this.module); // Get or register the stat in the database if (!registeredStats.contains(statType)) { synchronized (this.dsl) { StatsModel model = this.dsl.newRecord(TABLE_STATS).newStatsModel(statType.getName()); model.insert(); registeredStats.add(statType); } } this.stats.put(statType, stat); // Load configured fields for (Field field : statType.getFields()) { if (!field.isAnnotationPresent(Configured.class)) { return; } String name = field.getName(); String[] comment = {}; if (field.isAnnotationPresent(Name.class)) { Name nameAnnotation = field.getAnnotation(Name.class); name = nameAnnotation.value(); } if (field.isAnnotationPresent(Comment.class)) { Comment commentAnnotation = field.getAnnotation(Comment.class); comment = commentAnnotation.value(); } if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (section.hasKey(name)) { section.getNode(name).setComments(comment); field.set(stat, section.get(name)); } else { section.put(name, field.get(stat), comment); } } // Activate hook in the stat stat.activate(); // Register Schedulers for (Method method : stat.getClass().getMethods()) { if (!method.isAnnotationPresent(Scheduled.class)) { continue; } Scheduled annotation = method.getAnnotation(Scheduled.class); long interval; if (annotation.periodFinal()) { interval = annotation.interval(); } else { if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (!section.hasKey("tasks")) { section.put("tasks", new DynamicSection(converterManager), "Intervals for the tasks this statistic schedules"); } else { section.getNode("tasks") .setComments(new String[] { "Intervals for the tasks this statistic schedules" }); } DynamicSection tasks = (DynamicSection) section.get("tasks", DynamicSection.class); if (!tasks.hasKey(annotation.name())) { tasks.put(annotation.name(), annotation.interval(), annotation.comment()); } else { tasks.getNode(annotation.name()).setComments(annotation.comment()); } interval = (Long) tasks.get(annotation.name(), Long.class); } if (!this.tasks.containsKey(statType)) { this.tasks.put(statType, new HashSet<Integer>()); } Set<Integer> tasks = this.tasks.get(statType); Runnable wrapper = new ScheduledMethod(this.module.getLog(), stat, method); TaskManager taskManager = module.getCore().getTaskManager(); if (annotation.async()) { tasks.add(taskManager.runAsynchronousTimer(module, wrapper, 1, interval)); } else { tasks.add(taskManager.runTimer(module, wrapper, 1, interval)); } this.module.getLog().debug("Scheduled method {} at interval {}", annotation.name(), interval); } } catch (ReflectiveOperationException | ConversionException ex) { this.module.getLog().error(ex, "An error occurred while registering statistic"); } this.module.getLog().debug("Registered statistic {}.", statType.getSimpleName()); }