List of usage examples for java.lang Class getField
@CallerSensitive public Field getField(String name) throws NoSuchFieldException, SecurityException
From source file:com.p5solutions.core.utils.ReflectionUtility.java
/** * Gets the static value.//from w w w . jav a2 s. c om * * @param <T> the generic type * @param clazz the clazz * @param memberName the member name * @return the static value */ @SuppressWarnings("unchecked") public static <T> T getStaticValue(Class<?> clazz, String memberName) { try { Field field = clazz.getField(memberName); return (T) field.get(null); } catch (Exception e) { return null; } }
From source file:alpha.portal.webapp.taglib.ConstantsTei.java
/** * Return information about the scripting variables to be created. * // w ww . ja v a 2s .com * @param data * the input data * @return VariableInfo array of variable information */ @Override public VariableInfo[] getVariableInfo(final TagData data) { // loop through and expose all attributes final List<VariableInfo> vars = new ArrayList<VariableInfo>(); try { String clazz = data.getAttributeString("className"); if (clazz == null) { clazz = Constants.class.getName(); } final Class c = Class.forName(clazz); // if no var specified, get all if (data.getAttributeString("var") == null) { final Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (final Field field : fields) { final String type = field.getType().getName(); vars.add(new VariableInfo(field.getName(), ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } else { final String var = data.getAttributeString("var"); final String type = c.getField(var).getType().getName(); vars.add(new VariableInfo(c.getField(var).getName(), ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } catch (final Exception cnf) { this.log.error(cnf.getMessage()); cnf.printStackTrace(); } return vars.toArray(new VariableInfo[] {}); }
From source file:com.netscape.cmstools.cli.MainCLI.java
public void convertCertStatusList(String list, Collection<Integer> statuses) throws Exception { if (list == null) return;/*from w w w . j a v a 2 s. c o m*/ Class<SSLCertificateApprovalCallback.ValidityStatus> clazz = SSLCertificateApprovalCallback.ValidityStatus.class; for (String status : list.split(",")) { try { Field field = clazz.getField(status); statuses.add(field.getInt(null)); } catch (NoSuchFieldException e) { throw new Exception("Invalid cert status \"" + status + "\".", e); } } }
From source file:org.alfresco.repo.policy.PolicyComponentImpl.java
/** * Create a Policy Definition/* w ww . j a v a2 s .c om*/ * * @param policyIF the policy interface * @return the policy definition */ private PolicyDefinition createPolicyDefinition(Class policyIF) { // Extract Policy Namespace String namespaceURI = NamespaceService.DEFAULT_URI; try { Field metadata = policyIF.getField(ANNOTATION_NAMESPACE); if (!String.class.isAssignableFrom(metadata.getType())) { throw new PolicyException( "NAMESPACE metadata incorrectly specified in policy " + policyIF.getCanonicalName()); } namespaceURI = (String) metadata.get(null); } catch (NoSuchFieldException e) { // Assume default namespace } catch (IllegalAccessException e) { // Shouldn't get here (interface definitions must be accessible) } // Extract Policy Name Method[] methods = policyIF.getMethods(); if (methods.length != 1) { throw new PolicyException("Policy " + policyIF.getCanonicalName() + " must declare only one method"); } String name = methods[0].getName(); // Extract Policy Arguments Class[] paramTypes = methods[0].getParameterTypes(); Arg[] args = new Arg[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { // Extract Policy Arg args[i] = (i == 0) ? Arg.KEY : Arg.START_VALUE; try { Field argMetadata = policyIF.getField(ANNOTATION_ARG + i); if (!Arg.class.isAssignableFrom(argMetadata.getType())) { throw new PolicyException("ARG_" + i + " metadata incorrectly specified in policy " + policyIF.getCanonicalName()); } args[i] = (Arg) argMetadata.get(null); if (i == 0 && (!args[i].equals(Arg.KEY))) { throw new PolicyException( "ARG_" + i + " specified in policy " + policyIF.getCanonicalName() + " must be a key"); } } catch (NoSuchFieldException e) { // Assume default ARG configuration } catch (IllegalAccessException e) { // Shouldn't get here (interface definitions must be accessible) } } // Create Policy Definition return new PolicyDefinitionImpl(QName.createQName(namespaceURI, name), policyIF, args); }
From source file:net.gsantner.opoc.util.ContextUtils.java
/** * Get field from ${applicationId}.BuildConfig * May be helpful in libraries, where a access to * BuildConfig would only get values of the library * rather than the app ones. It awaits a string resource * of the package set in manifest (root element). * Falls back to applicationId of the app which may differ from manifest. *//*from ww w. ja va2 s. co m*/ public Object getBuildConfigValue(String fieldName) { String pkg = getPackageIdManifest() + ".BuildConfig"; try { Class<?> c = Class.forName(pkg); return c.getField(fieldName).get(null); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:de.static_interface.sinksql.SqlDatabase.java
protected String addForeignKey(String sql, String name, Class<? extends AbstractTable> targetClass, String columnName, CascadeAction onUpdate, CascadeAction onDelete) { char bt = getBacktick(); String tablename;//ww w . j a va 2 s . co m try { tablename = targetClass.getField("TABLE_NAME").get(null).toString(); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException("Static String Field TABLE_NAME was not declared in table wrapper class " + targetClass.getName() + "!", e); } sql += "FOREIGN KEY (" + bt + name + bt + ") REFERENCES " + getConnectionInfo().getTablePrefix() + tablename + " (" + bt + columnName + bt + ")"; sql += " ON UPDATE " + onUpdate.toSql() + " ON DELETE " + onDelete.toSql(); sql += ","; return sql; }
From source file:ua.com.manometer.jasperreports.AbstractJasperReportsView.java
/** * Convert the given fully qualified field name to a corresponding * JRExporterParameter instance.//from w w w . ja v a 2s . c o m * @param fqFieldName the fully qualified field name, consisting * of the class name followed by a dot followed by the field name * (e.g. "net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI") * @return the corresponding JRExporterParameter instance */ protected JRExporterParameter convertToExporterParameter(String fqFieldName) { int index = fqFieldName.lastIndexOf('.'); if (index == -1 || index == fqFieldName.length()) { throw new IllegalArgumentException("Parameter name [" + fqFieldName + "] is not a valid static field. " + "The parameter name must map to a static field such as " + "[net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI]"); } String className = fqFieldName.substring(0, index); String fieldName = fqFieldName.substring(index + 1); try { Class cls = ClassUtils.forName(className, getApplicationContext().getClassLoader()); Field field = cls.getField(fieldName); if (JRExporterParameter.class.isAssignableFrom(field.getType())) { try { return (JRExporterParameter) field.get(null); } catch (IllegalAccessException ex) { throw new IllegalArgumentException("Unable to access field [" + fieldName + "] of class [" + className + "]. " + "Check that it is static and accessible."); } } else { throw new IllegalArgumentException("Field [" + fieldName + "] on class [" + className + "] is not assignable from JRExporterParameter - check the type of this field."); } } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( "Class [" + className + "] in key [" + fqFieldName + "] could not be found."); } catch (NoSuchFieldException ex) { throw new IllegalArgumentException("Field [" + fieldName + "] in key [" + fqFieldName + "] could not be found on class [" + className + "]."); } }
From source file:edu.brown.api.BenchmarkConfig.java
@SuppressWarnings("unchecked") public void loadConfigFile(File path) { try {/*from w w w .j a v a2 s. c om*/ this.config = new PropertiesConfiguration(benchmark_conf_path); } catch (Exception ex) { throw new RuntimeException("Failed to load benchmark configuration file " + benchmark_conf_path); } Class<?> confClass = this.getClass(); for (Object key : CollectionUtil.iterable(this.config.getKeys())) { String f_name = key.toString(); String f_value = this.config.getString(f_name); // Always store whatever the property as a client parameter String paramName = (HStoreConstants.BENCHMARK_PARAM_PREFIX + f_name).toUpperCase(); LOG.debug(String.format("Passing benchmark parameter to clients: %s = %s", paramName, f_value)); clientParameters.put(paramName, f_value); Field f = null; try { f = confClass.getField(f_name); } catch (Exception ex) { // XXX LOG.warn("Invalid configuration property '" + f_name + "'. Ignoring..."); continue; } assert (f != null); Class<?> f_class = f.getType(); Object value = null; if (f_class.equals(int.class)) { value = this.config.getInt(f_name); } else if (f_class.equals(long.class)) { value = this.config.getLong(f_name); } else if (f_class.equals(double.class)) { value = this.config.getDouble(f_name); } else if (f_class.equals(boolean.class)) { value = this.config.getBoolean(f_name); } else if (f_class.equals(String.class)) { value = this.config.getString(f_name); } else { LOG.warn(String.format("Unexpected value type '%s' for property '%s'", f_class.getSimpleName(), f_name)); } try { f.set(this, value); LOG.info(String.format("SET %s = %s", f_name, value)); } catch (Exception ex) { throw new RuntimeException("Failed to set value '" + value + "' for field '" + f_name + "'", ex); } } // FOR }
From source file:com.easemob.chatuidemo.activity.BaseChatActivity.java
/** * ?gridview?view/*from www. ja v a 2s. c om*/ * * @param i * @return */ private View getGridChildView(int i) { View view = View.inflate(this, R.layout.expression_gridview, null); ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview); List<String> list = new ArrayList<String>(); if (i == 1) { List<String> list1 = reslist.subList(0, 20); list.addAll(list1); } else if (i == 2) { list.addAll(reslist.subList(20, reslist.size())); } list.add("delete_expression"); final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list); gv.setAdapter(expressionAdapter); gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String filename = expressionAdapter.getItem(position); try { // ???? // ????? // if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) { if (filename != "delete_expression") { // ? // ????SmileUtils Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils"); Field field = clz.getField(filename); mEditTextContent .append(SmileUtils.getSmiledText(BaseChatActivity.this, (String) field.get(null))); } else { // if (!TextUtils.isEmpty(mEditTextContent.getText())) { int selectionStart = mEditTextContent.getSelectionStart();// ?? if (selectionStart > 0) { String body = mEditTextContent.getText().toString(); String tempStr = body.substring(0, selectionStart); int i = tempStr.lastIndexOf("[");// ??? if (i != -1) { CharSequence cs = tempStr.substring(i, selectionStart); if (SmileUtils.containsKey(cs.toString())) mEditTextContent.getEditableText().delete(i, selectionStart); else mEditTextContent.getEditableText().delete(selectionStart - 1, selectionStart); } else { mEditTextContent.getEditableText().delete(selectionStart - 1, selectionStart); } } } // } } } catch (Exception e) { } } }); return view; }
From source file:com.android.tools.idea.uibuilder.model.NlComponent.java
@NotNull public Insets getMargins() { if (myMargins == null) { if (viewInfo == null) { return Insets.NONE; }//from ww w .j a v a2 s . c o m try { Object layoutParams = viewInfo.getLayoutParamsObject(); Class<?> layoutClass = layoutParams.getClass(); int left = fixDefault(layoutClass.getField("leftMargin").getInt(layoutParams)); int top = fixDefault(layoutClass.getField("topMargin").getInt(layoutParams)); int right = fixDefault(layoutClass.getField("rightMargin").getInt(layoutParams)); int bottom = fixDefault(layoutClass.getField("bottomMargin").getInt(layoutParams)); // Doesn't look like we need to read startMargin and endMargin here; // ViewGroup.MarginLayoutParams#doResolveMargins resolves and assigns values to the others if (left == 0 && top == 0 && right == 0 && bottom == 0) { myMargins = Insets.NONE; } else { myMargins = new Insets(left, top, right, bottom); } } catch (Throwable e) { myMargins = Insets.NONE; } } return myMargins; }