Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

In this page you can find the example usage for java.lang Class getField.

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Used to find the property type of a given attribute regardless of whether the attribute exists as a field or only
 * as a getter method./*from ww  w . j  a v  a  2s  . c o m*/
 * 
 * <p>(Not using PropertyUtils since it required an instance of the class.)</p>
  *
  * @param clazz the class that contains the property.
  * @param propertyName the name of the property.
  * @return the type of the property.
 */
protected Class<?> getTypeOfProperty(Class<?> clazz, String propertyName) {
    try {
        Field f = clazz.getField(propertyName);
        return f.getType();
    } catch (Exception e) {
        // Do nothing = field does not exist
    }
    try {
        Method m = clazz.getMethod("get" + StringUtils.capitalize(propertyName));
        return m.getReturnType();
    } catch (Exception e) {
        // Do nothing = method does not exist
    }
    try {
        Method m = clazz.getMethod("is" + StringUtils.capitalize(propertyName));
        return m.getReturnType();
    } catch (Exception e) {
        // Do nothing = method does not exist
    }
    return null;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

private Object attemptToConvertStringToEnum(Class<?> requiredType, String trimmedValue,
        Object currentConvertedValue) {
    Object convertedValue = currentConvertedValue;

    if (Enum.class.equals(requiredType)) {
        // target type is declared as raw enum, treat the trimmed value as <enum.fqn>.FIELD_NAME
        int index = trimmedValue.lastIndexOf(".");
        if (index > -1) {
            String enumType = trimmedValue.substring(0, index);
            String fieldName = trimmedValue.substring(index + 1);
            ClassLoader loader = this.targetObject.getClass().getClassLoader();
            try {
                Class<?> enumValueType = loader.loadClass(enumType);
                Field enumField = enumValueType.getField(fieldName);
                convertedValue = enumField.get(null);
            } catch (ClassNotFoundException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Enum class [" + enumType + "] cannot be loaded from [" + loader + "]", ex);
                }//ww  w . j  a  v a 2s .c  o  m
            } catch (Throwable ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Field [" + fieldName + "] isn't an enum value for type [" + enumType + "]",
                            ex);
                }
            }
        }
    }

    if (convertedValue == currentConvertedValue) {
        // Try field lookup as fallback: for JDK 1.5 enum or custom enum
        // with values defined as static fields. Resulting value still needs
        // to be checked, hence we don't return it right away.
        try {
            Field enumField = requiredType.getField(trimmedValue);
            convertedValue = enumField.get(null);
        } catch (Throwable ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Field [" + convertedValue + "] isn't an enum value", ex);

            }
        }
    }

    return convertedValue;
}

From source file:org.musicrecital.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * @param data the input data/*w ww  .  j a v  a2s . co m*/
 * @return VariableInfo array of variable information
 */
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                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 {
            String var = data.getAttributeString("var");
            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 (Exception cnf) {
        log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryGeneratorTest.java

@Test
public void validateContentOfErrorDataCollections() throws Exception {
    String errorDataCOllectionClassName = "org.ebayopensource.turmeric.test.errorlibrary.turmericruntime.ErrorDataCollection";
    String sampleErrorName = "svc_factory_custom_ser_no_bound_type";

    // Initialize testing paths
    MavenTestingUtils.ensureEmpty(testingdir);
    File rootDir = TestResourceUtil.copyResourceRootDir("errorLibrary/TestErrorLibrary", testingdir);
    File binDir = new File(rootDir, "bin");
    File gensrcDir = new File(rootDir, "gen-src");

    MavenTestingUtils.ensureDirExists(binDir);
    MavenTestingUtils.ensureDirExists(gensrcDir);

    // @formatter:off
    String pluginParameters[] = { "-gentype", "genTypeDataCollection", "-pr", rootDir.getAbsolutePath(),
            "-domain", "TurmericRuntime", "-errorlibname", "TestErrorLibrary" };
    // @formatter:on

    performDirectCodeGen(pluginParameters);

    Class<?> errDataCollection = compileGeneratedFile(errorDataCOllectionClassName, gensrcDir, binDir);
    Assert.assertThat("errDataCollection", errDataCollection, notNullValue());
    Assert.assertThat(errDataCollection.getName(), is(errorDataCOllectionClassName));

    Field member = errDataCollection.getField(sampleErrorName);
    Assert.assertThat("member", member, notNullValue());

    Assert.assertThat("member.type", member.getType().getName(), is(CommonErrorData.class.getName()));
    Assert.assertThat("member.isFinal", Modifier.isFinal(member.getModifiers()), is(true));
    Assert.assertThat("member.isPublic", Modifier.isPublic(member.getModifiers()), is(true));
    Assert.assertThat("member.isStatic", Modifier.isStatic(member.getModifiers()), is(true));
    CommonErrorData edata = (CommonErrorData) member.get(null);
    Assert.assertThat("CommonErrorData", edata, notNullValue());
    Assert.assertThat("CommonErrorData.category", edata.getCategory(), is(ErrorCategory.SYSTEM));
    Assert.assertThat("CommonErrorData.severity", edata.getSeverity(), is(ErrorSeverity.ERROR));
    Assert.assertThat("CommonErrorData.subdommain", edata.getSubdomain(), is("Config"));
}

From source file:com.datatorrent.lib.join.POJOJoinOperator.java

/**
 * Populate the getters from the input class
 *
 * @param isLeft isLeft specifies whether the class is left or right
 *//*from  w  w  w . ja va2 s . co  m*/
private void populateGettersFromInput(boolean isLeft) {
    Class inputClass;
    int idx;
    StoreContext store;
    if (isLeft) {
        idx = 0;
        inputClass = leftClass;
        store = leftStore;
    } else {
        idx = 1;
        inputClass = rightClass;
        store = rightStore;
    }
    String key = store.getKeys();
    String timeField = store.getTimeFields();
    String[] fields = store.getIncludeFields();

    // Create getter for the key field
    try {
        Class c = ClassUtils.primitiveToWrapper(inputClass.getField(key).getType());
        keyGetters[idx] = PojoUtils.createGetter(inputClass, key, c);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }

    // Create getter for time field
    if (timeField != null) {
        try {
            Class c = ClassUtils.primitiveToWrapper(inputClass.getField(timeField).getType());
            timeGetters[idx] = PojoUtils.createGetter(inputClass, timeField, c);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    fieldMap[idx] = new LinkedList<FieldObjectMap>();
    List<FieldObjectMap> fieldsMap = fieldMap[idx];
    // Create getters for the include fields
    for (String f : fields) {
        try {
            Field field = inputClass.getField(f);
            Class c;
            if (field.getType().isPrimitive()) {
                c = ClassUtils.primitiveToWrapper(field.getType());
            } else {
                c = field.getType();
            }
            FieldObjectMap fm = new FieldObjectMap();
            fm.get = PojoUtils.createGetter(inputClass, f, c);
            fm.set = PojoUtils.createSetter(outputClass, f, c);
            fieldsMap.add(fm);
        } catch (Throwable e) {
            throw new RuntimeException("Failed to populate gettter for field: " + f, e);
        }
    }
}

From source file:org.openhie.openempi.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * @param data the input data//from  w  w  w. j a  v  a2s  .c om
 * @return VariableInfo array of variable information
 */
@SuppressWarnings("unchecked")
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                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 {
            String var = data.getAttributeString("var");
            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 (Exception cnf) {
        log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:com.gisgraphy.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * /*from  ww w.  java  2  s. co  m*/
 * @param data
 *                the input data
 * @return VariableInfo array of variable information
 */
@Override
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class<?> c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                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 {
            String var = data.getAttributeString("var");
            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 (Exception cnf) {
        log.error(cnf.getMessage());
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:org.apache.axis.utils.JavaUtils.java

/**
 * Determines if the Class is a Holder class. If so returns Class of held type
 * else returns null//from w  w w.j  ava 2 s . c om
 * @param type the suspected Holder Class
 * @return class of held type or null
 */
public static Class getHolderValueType(Class type) {
    if (type != null) {
        Class[] intf = type.getInterfaces();
        boolean isHolder = false;
        for (int i = 0; i < intf.length && !isHolder; i++) {
            if (intf[i] == javax.xml.rpc.holders.Holder.class) {
                isHolder = true;
            }
        }
        if (isHolder == false) {
            return null;
        }

        // Holder is supposed to have a public value field.
        java.lang.reflect.Field field;
        try {
            field = type.getField("value");
        } catch (Exception e) {
            field = null;
        }
        if (field != null) {
            return field.getType();
        }
    }
    return null;
}

From source file:com.fanxin.app.fx.ChatActivity.java

/**
 * ?gridview?view/*w  w  w. j a  v  a2 s  .  co m*/
 * 
 * @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
                        @SuppressWarnings("rawtypes")
                        Class clz = Class.forName("com.fanxin.app.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        mEditTextContent
                                .append(SmileUtils.getSmiledText(ChatActivity.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:cn.wyx.android.swipeback.swipe.SwipeBackLayout.java

public int getStatusBarHeight() {
    Class<?> c = null;
    Object obj = null;/*from   w w w.  j  a  v a  2  s . com*/
    Field field = null;
    int x = 0, statusBarHeight = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        obj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(obj).toString());
        statusBarHeight = getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return statusBarHeight;
}