Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

private static void clearMap(Class cl, Object obj, String name)
        throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

    Field field = cl.getDeclaredField(name);
    field.setAccessible(true);//  w w  w  .  j  a  va  2  s.  c om

    Object cache = field.get(obj);

    synchronized (cache) {
        Class ccl = cache.getClass();
        Method clearMethod = ccl.getMethod("clear");
        clearMethod.invoke(cache);
    }
}

From source file:com.bizcreator.core.config.FieldInfo.java

Field findField(Class clazz) {
    Field field = null;//from   w  w  w  . j  av  a 2  s .c o m

    Class candidateClass = clazz;
    while ((candidateClass != null) && (field == null)) {

        try {
            field = candidateClass.getDeclaredField(propertyName);
        } catch (Exception e) {
            candidateClass = candidateClass.getSuperclass();
        }
    }

    if (field == null) {
        BaseException e = new BaseException(
                "couldn't find field '" + propertyName + "' in class '" + clazz.getName() + "'");
        log.error("", e);
        throw e;
    }

    return field;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONSerializable deSerialize(Class clz, JSONObject jsonObj)
        throws JSONSerializationException, JSONException {
    Iterator iter = jsonObj.keys();

    if (!JSONSerializable.class.isAssignableFrom(clz)) {
        throw new JSONSerializationException(clz + " is not an instance of " + JSONSerializable.class);
    }//from w  w w  .j av  a  2 s.  co m

    JSONSerializable retObj;
    try {
        retObj = (JSONSerializable) clz.newInstance();
    } catch (Exception e1) {
        throw new JSONSerializationException(
                "trouble with no-arg instantiation of " + clz.toString() + ": " + e1.getMessage(), e1);
    }

    if (JSONExternalizable.class.isAssignableFrom(clz)) {
        ((JSONExternalizable) retObj).fromJSON(jsonObj);
        return retObj;
    }

    while (iter.hasNext()) {
        String key = (String) iter.next();

        try {
            Field f = clz.getDeclaredField(key);
            if (f != null) {
                f.setAccessible(true);
                Class type = f.getType();

                if (type.isArray()) {
                    JSONArray array = jsonObj.getJSONArray(key);
                    int len = array.length();
                    Class cls = type.getComponentType();

                    Object newArray = Array.newInstance(cls, len);
                    for (int k = 0; k < len; ++k) {
                        loadObject(newArray, cls, k, array);
                    }
                    f.set(retObj, newArray);
                } else {
                    loadObject(retObj, f, jsonObj);
                }
            }
        } catch (Exception e) {
            throw new JSONSerializationException(e.getMessage(), e);
        }
    }

    return retObj;
}

From source file:com.glaf.core.util.ReflectUtils.java

/**
 * Returns the field of the given class or null if it doesnt exist.
 *///from   www.j  a v  a2 s. c  om
public static Field getField(String fieldName, Class<?> clazz) {
    Field field = null;
    try {
        field = clazz.getDeclaredField(fieldName);
    } catch (SecurityException e) {
        throw new RuntimeException(
                "not allowed to access field " + field + " on class " + clazz.getCanonicalName());
    } catch (NoSuchFieldException e) {
        // for some reason getDeclaredFields doesnt search superclasses
        // (which getFields() does ... but that gives only public fields)
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null) {
            return getField(fieldName, superClass);
        }
    }
    return field;
}

From source file:nc.noumea.mairie.annuairev2.saisie.viewmodel.ContainsSimpleListModel.java

public ContainsSimpleListModel(List<T> data, Class<T> clazz, String property) {
    super(data);/*from   w ww  . j a va2  s .c  om*/
    this.clazz = clazz;
    this.property = property;

    try {
        this.field = clazz.getDeclaredField(property);
    } catch (NoSuchFieldException e) {
        LOGGER.error(e.toString(), e);
        try {
            this.field = clazz.getSuperclass().getDeclaredField(property);
        } catch (NoSuchFieldException e1) {
            LOGGER.error(e1.toString(), e1);
        }
    }

    field.setAccessible(true);
}

From source file:com.comcast.cats.EnvironmentFactory.java

private Field getStubField(final Class<?> clazz, final String fieldName) {
    Field field = null;//from   w w w. ja  v  a2  s . co  m
    try {
        field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    return field;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * <p>Get a static property value, which has a public static getter or is just a public static field.</p>
 *
 * @param clazz The class to check for static property
 * @param name The property name//  w  w w.java  2s  . c  o m
 * @return The value if there is one, or null if unset OR there is no such property
 */
public static Object getStaticPropertyValue(Class clazz, String name) {
    Object value = null;
    Method getter = BeanUtils.findDeclaredMethod(clazz, getGetterName(name), null);
    try {
        if (getter != null) {
            value = getter.invoke(null, new Object[0]);
        } else {
            Field f = clazz.getDeclaredField(name);
            if (f != null) {
                value = f.get(null);
            }
        }
    } catch (Exception e) {
        value = null;
    }
    return value;
}

From source file:ddf.security.command.EncryptCommandTest.java

private void setPlainTextValueField(EncryptCommand encryptCommand, String value) {
    final String plainTextValueField = "plainTextValue";
    final Class<? extends EncryptCommand> clazz = encryptCommand.getClass();

    try {//from w ww . j  av a  2s .com
        final Field field = clazz.getDeclaredField(plainTextValueField);
        field.setAccessible(true);
        field.set(encryptCommand, value);
    } catch (SecurityException e) {
        LOGGER.debug("Security exception setting field value", e);
        fail(e.getMessage());
    } catch (NoSuchFieldException e) {
        LOGGER.debug("No such field exception setting field value", e);
        fail(e.getMessage());
    } catch (IllegalArgumentException e) {
        LOGGER.debug("Illegal argument exception setting field value", e);
        fail(e.getMessage());
    } catch (IllegalAccessException e) {
        LOGGER.debug("Illegal exception exception setting field value", e);
        fail(e.getMessage());
    }

}

From source file:info.raack.appliancelabeler.datacollector.EnergyDataLoaderTest.java

@Before
public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, JAXBException, SAXException {
    dataService = mock(DataService.class);
    database = mock(Database.class);
    errorService = mock(ErrorService.class);
    configurationLoaders = new ArrayList<ConfigurationLoader>();
    emailSender = mock(EmailSender.class);

    loader = new EnergyDataLoader();
    Class<?> c = loader.getClass();
    Field f = c.getDeclaredField("dataService");
    f.setAccessible(true);//from   w w  w .  j  av  a 2s  .com
    f.set(loader, dataService);

    f = c.getDeclaredField("configurationLoaders");
    f.setAccessible(true);
    f.set(loader, configurationLoaders);

    f = c.getDeclaredField("errorService");
    f.setAccessible(true);
    f.set(loader, errorService);

    f = c.getDeclaredField("database");
    f.setAccessible(true);
    f.set(loader, database);

    f = c.getDeclaredField("emailSender");
    f.setAccessible(true);
    f.set(loader, emailSender);

    f = c.getDeclaredField("energyPollingFrequency");
    f.setAccessible(true);
    f.set(loader, 30);

    f = c.getDeclaredField("energylabelerUrl");
    f.setAccessible(true);
    f.set(loader, "http://www.energylabelerurl.com");
}

From source file:org.jsonschema2pojo.integration.config.IncludeAccessorsIT.java

@Test
public void beansWithoutAccessorsRoundTripJsonCorrectly()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException,
        InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("includeAccessors", false));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Object instance = generatedType.newInstance();
    generatedType.getDeclaredField("a").set(instance, 12);
    generatedType.getDeclaredField("b").set(instance, 1.12);
    generatedType.getDeclaredField("c").set(instance, true);

    ObjectMapper objectMapper = new ObjectMapper();
    String instanceAsJson = objectMapper.writeValueAsString(instance);

    Object instanceAfterRoundTrip = objectMapper.readValue(instanceAsJson, generatedType);

    assertThat(instanceAfterRoundTrip, is(equalTo(instance)));

}