List of usage examples for java.lang Class getField
@CallerSensitive public Field getField(String name) throws NoSuchFieldException, SecurityException
From source file:com.aliyun.openservices.odps.console.utils.CommandParserUtils.java
public static void printHelpInfo(List<String> keywords) { Map<String, Integer> matched = new HashMap<String, Integer>() { };//from w w w.java 2 s .co m List<String> allCommands = new ArrayList<String>(); if (ecList == null) { ecList = PluginUtil.getExtendCommandList(); } for (PluginPriorityCommand command : ecList) { allCommands.add(command.getCommandName()); } for (String commandName : allCommands) { try { Class<?> commandClass = Class.forName(commandName, false, classLoader); Field tags_field = commandClass.getField(HELP_TAGS_FIELD); String[] tags = (String[]) tags_field.get(null); int count = 0; for (String tag : tags) { for (String keyword : keywords) { if (tag.equalsIgnoreCase(keyword)) { count++; break; } } } if (count != 0) { matched.put(commandName, count); } } catch (ClassNotFoundException e) { // Console??AssertionError //throw new AssertionError("Cannot find the command:" + commandName); e.printStackTrace(); } catch (NoSuchFieldException e) { // Ignore } catch (IllegalAccessException e) { // Ignore } } // Print the help info of the command(s) whose tags match most keywords boolean found = false; System.out.println(); for (int i = keywords.size(); i >= 1; i--) { for (Map.Entry<String, Integer> entry : matched.entrySet()) { if (i == entry.getValue()) { try { Class<?> commandClass = Class.forName(entry.getKey(), false, classLoader); Method printMethod = commandClass.getDeclaredMethod(HELP_PRINT_METHOD, new Class<?>[] { PrintStream.class }); printMethod.invoke(null, System.out); found = true; } catch (ClassNotFoundException e) { // Console??AssertionError throw new AssertionError("Cannot find the command:" + entry.getKey()); } catch (NoSuchMethodException e) { // Ignore } catch (IllegalAccessException e) { // Ignore } catch (InvocationTargetException e) { // Ignore } } } if (found) { break; } } System.out.println(); }
From source file:de.mpg.escidoc.pubman.util.InternationalizationHelper.java
/** * Return any bean stored in application scope under the specified name. * @param cls The bean class./*from ww w. ja v a 2 s . c o m*/ * @return the actual or new bean instance */ public static synchronized Object getApplicationBean(final Class<?> cls) { String name = null; try { name = (String) cls.getField("BEAN_NAME").get(new String()); if (FacesBean.class.getName().equals(name)) { logger.warn("Bean class " + cls.getName() + " appears to have no individual BEAN_NAME."); } } catch (Exception e) { throw new RuntimeException("Error getting bean name of " + cls, e); } Object result = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(name); logger.debug("Getting bean " + name + ": " + result); if (result == null) { try { logger.debug("Creating new application bean: " + name); Object newBean = cls.newInstance(); FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(name, newBean); return newBean; } catch (Exception e) { throw new RuntimeException("Error creating new bean of type " + cls, e); } } else { return result; } }
From source file:org.jdbcluster.JDBClusterUtil.java
/** * returns Filed object for Properties. Iterates over all superclasses Find * a Field with the given Field name and the given parameter types, declared * on the given class or one of its superclasses. Prefers public Field, but * will return a protected, package access, or private Field too. * <p>/* w ww .j av a 2s . c om*/ * Checks <code>Class.getField</code> first, falling back to * <code>getDeclaredField</code>. * * @param propName * path to property * @param c * Class object * @return Field instance */ static public Field getField(String propName, Class clazz) { Assert.notNull(clazz, "clazz may not be null"); Assert.hasLength(propName, "obj may not be null or \"\""); Field f = null; try { f = clazz.getField(propName); } catch (SecurityException e) { throw new ConfigurationException( "cant get field for property [" + propName + "] with the specified name for " + clazz.getName(), e); } catch (NoSuchFieldException e) { return JDBClusterUtil.getDeclaredField(propName, clazz); } return f; }
From source file:it.nicola_amatucci.util.Json.java
public static <T> JSONObject json_from_object(Object o, Class<T> objClass) throws Exception { JSONObject json = new JSONObject(); Field[] fields = objClass.getFields(); try {//from ww w. ja va 2 s. c o m for (Field field : fields) { //valore del campo try { String typeName = field.getType().getSimpleName(); //in base al tipo richiamo l'opportuna funzione if (typeName.equals("String") || typeName.equals("boolean") || typeName.equals("int") || typeName.equals("long") || typeName.equals("double")) { json.put(field.getName(), objClass.getField(field.getName()).get(o)); } else if (typeName.equals("Date")) { json.put(field.getName(), new SimpleDateFormat(Json.DATA_FORMAT) .format((java.util.Date) objClass.getField(field.getName()).get(o))); } else if (field.getType().isArray()) { try { JSONArray array = new JSONArray(); Class c = Class.forName(field.getType().getName()).getComponentType(); Object[] objArray = (Object[]) objClass.getField(field.getName()).get(o); for (int i = 0; i < objArray.length; i++) { array.put(json_from_object(objArray[i], c)); } json.put(field.getName(), array); } catch (Exception e) { throw e; } } else { JSONObject jsonObj = json_from_object(objClass.getField(field.getName()).get(o), field.getType()); json.put(field.getName(), jsonObj); } } catch (Exception e) { throw e; } } } catch (Exception e) { throw e; } return json; }
From source file:edu.cmu.cs.lti.util.uima.UimaConvenience.java
/** * Identifies the number of annotations of a given type in the specified JCas. * /* w ww . j av a 2s. c om*/ * @param aJCas * @param clazz * @return * @throws CASRuntimeException */ public static int numberOfAnnotations(final JCas aJCas, final Class clazz) throws CASRuntimeException { try { final int type = clazz.getField("type").getInt(clazz); return aJCas.getAnnotationIndex(type).size(); } catch (SecurityException e) { throw new CASRuntimeException(e); } catch (IllegalAccessException e) { throw new CASRuntimeException(e); } catch (NoSuchFieldException e) { throw new CASRuntimeException(e); } }
From source file:net.aepik.alasca.core.ldap.Schema.java
/** * Return syntaxes short name./*from w ww . ja v a 2 s .com*/ */ public static String[] getSyntaxeNames(String[] names) { String[] syntaxes = names; try { String packageName = getSyntaxPackageName(); for (int i = 0; i < syntaxes.length; i++) { Class object = Class.forName(packageName + "." + syntaxes[i]); Field field = object.getField("SHORTNAME"); if (field != null) { syntaxes[i] = field.get(null).toString(); } } } catch (Exception e) { e.printStackTrace(); } return syntaxes; }
From source file:net.aepik.alasca.core.ldap.Schema.java
/** * Return a syntax object by name./*from w w w .j ava 2s .com*/ */ public static SchemaSyntax getSyntax(String name) { try { String packageName = getSyntaxPackageName(); for (String syntaxe : getSyntaxes()) { Class object = Class.forName(packageName + "." + syntaxe); Field field = object.getField("SHORTNAME"); if (field != null && name.equals(field.get(null).toString())) { @SuppressWarnings("unchecked") SchemaSyntax o = ((Class<SchemaSyntax>) Class.forName(packageName + "." + syntaxe)) .newInstance(); return o; } } for (String syntaxe : getSyntaxes()) { if (name.equals(syntaxe)) { @SuppressWarnings("unchecked") SchemaSyntax o = ((Class<SchemaSyntax>) Class.forName(packageName + "." + syntaxe)) .newInstance(); return o; } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.eclipse.wb.internal.core.xml.model.property.editor.StaticFieldPropertyEditor.java
/** * Check field's, if field does not exist, then remove it from array. *///from w w w . ja v a2s. co m private static String[] cleanUpFieldDescriptions(Class<?> m_class, String[] fieldDescriptions) throws Exception { List<String> newFieldDescriptions = Lists.newArrayList(); // check all fields for (String fieldDescription : fieldDescriptions) { // skip special cases if ("*remove".equals(fieldDescription)) { newFieldDescriptions.add(fieldDescription); continue; } // prepare field name String name = getFieldName(fieldDescription); // check exist field try { m_class.getField(name); } catch (NoSuchFieldException e) { continue; } // OK, valid field newFieldDescriptions.add(fieldDescription); } // return as array return newFieldDescriptions.toArray(new String[newFieldDescriptions.size()]); }
From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java
public static <T> T toXmlEnum(Class<T> expectedType, String stringValue) { if (stringValue == null) { return null; }//w ww . ja va 2 s . c o m for (T enumConstant : expectedType.getEnumConstants()) { Field field; try { field = expectedType.getField(((Enum) enumConstant).name()); } catch (SecurityException e) { throw new IllegalArgumentException( "Error getting field from '" + enumConstant + "' in " + expectedType, e); } catch (NoSuchFieldException e) { throw new IllegalArgumentException( "Error getting field from '" + enumConstant + "' in " + expectedType, e); } XmlEnumValue annotation = field.getAnnotation(XmlEnumValue.class); if (annotation.value().equals(stringValue)) { return enumConstant; } } throw new IllegalArgumentException("No enum value '" + stringValue + "' in " + expectedType); }
From source file:org.eclipse.wb.internal.core.model.property.editor.StaticFieldPropertyEditor.java
/** * Check field's, if field does not exist, then remove it from array. *//*from ww w . j a v a 2s . co m*/ private static String[] cleanUpFieldDescriptions(IWarningConsumer logger, Class<?> m_class, String[] fieldDescriptions) throws Exception { List<String> newFieldDescriptions = Lists.newArrayList(); // check all fields for (String fieldDescription : fieldDescriptions) { // skip special cases if ("*remove".equals(fieldDescription)) { newFieldDescriptions.add(fieldDescription); continue; } // prepare field name String name = getFieldName(fieldDescription); // check exist field try { m_class.getField(name); } catch (NoSuchFieldException e) { String message = MessageFormat.format("Can not find field {0}.{1}.", m_class.getName(), name); logger.addWarning(message, e); continue; } // OK, valid field newFieldDescriptions.add(fieldDescription); } // return as array return newFieldDescriptions.toArray(new String[newFieldDescriptions.size()]); }