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:net.ostis.sc.memory.SCKeynodesBase.java

private static boolean checkKeynodesNumberPatternURI(SCSession session, Class<?> klass, Field field)
        throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
    KeynodesNumberPatternURI patternURI = field.getAnnotation(KeynodesNumberPatternURI.class);

    if (patternURI != null) {
        String[] comp = URIUtils.splitByIdtf(patternURI.patternURI());

        SCSegment segment = session.openSegment(comp[0]);

        List<SCAddr> keynodes = new LinkedList<SCAddr>();
        for (int i = patternURI.startIndex(); i <= patternURI.endIndex(); ++i) {
            String keynodeName = MessageFormat.format(comp[1], i);

            SCAddr keynode = session.findByIdtf(keynodeName, segment);
            Validate.notNull(keynode, keynodeName);

            keynodes.add(keynode);//from   w  ww  .ja  va  2s  .  co m

            String fieldName = MessageFormat.format(patternURI.patternName(), i);
            Field keynodeField = klass.getField(fieldName);
            keynodeField.set(null, keynode);

            if (log.isDebugEnabled())
                log.debug(comp[0] + "/" + keynodeName + " --> " + keynodeField.getName());
        }

        field.set(null, (SCAddr[]) keynodes.toArray(new SCAddr[keynodes.size()]));

        if (log.isDebugEnabled())
            log.debug(patternURI.patternURI() + " --> " + field.getName());

        return true;
    } else {
        return false;
    }
}

From source file:org.jboss.dashboard.ui.components.permissions.PermissionsAssignerFormatter.java

protected void renderActions() throws Exception {
    renderFragment("rolesSelection");
    Class permissionClass = getPermissionsHandler().getPermissionClass();
    List actionList = (List) permissionClass.getField("LIST_OF_ACTIONS").get(permissionClass);
    Method actionNameMethod = null;
    try {//from   w  w w.  j  a  va  2 s  .  co  m
        actionNameMethod = permissionClass.getMethod("getActionName",
                new Class[] { String.class, String.class, Locale.class });
    } catch (NoSuchMethodException cnfe) {
        log.warn(
                "Permission class doesn't provide method getActionName(String, String, Locale) to get action names.");
    }
    for (int i = 0; i < actionList.size(); i++) {
        String actionName = (String) actionList.get(i);
        String actionDescription = actionName;
        if (actionNameMethod != null) {
            actionDescription = (String) actionNameMethod.invoke(null,
                    new Object[] { permissionClass.getName(), actionName, getLocale() });
        }
        setAttribute("actionDescription", actionDescription);
        setAttribute("actionName", actionName);
        //setAttribute("className", i % 2 == 1 ? "skn-even_row" : "skn-odd_row");
        renderFragment("outputAction");
    }
}

From source file:com.datatorrent.lib.util.PojoUtils.java

/**
 * Return the getter expression for the given field.
 * <p>//  w  w w  .  j  a  v a 2  s.com
 * If the field is a public member, the field name is used else the getter function. If no matching field or getter
 * method is found, the expression is returned unmodified.
 *
 * @param pojoClass class to check for the field
 * @param fieldExpression field name expression
 * @param exprClass expected field type
 * @return java code fragment
 */
private static String getSingleFieldGetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaReturnStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32,
            exprClass);
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(field.getType(), exprClass)) {
            return code.append(field.getName()).getStatement();
        }
        logger.debug("Field {} can not be assigned to {}. Proceeding to locate a getter method.", field,
                exprClass);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    }

    String methodName = GET + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to {}. Proceeding to locate another getter method.",
                pojoClass, methodName, method.getReturnType(), exprClass);
    } catch (NoSuchMethodException | SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass,
                methodName);
    }

    methodName = IS + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to {}. Proceeding with the original expression {}.",
                pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression);
    } catch (NoSuchMethodException | SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    }

    return code.append(fieldExpression).getStatement();
}

From source file:org.apache.geode.internal.cache.rollingupgrade.RollingUpgradeDUnitTest.java

public static void createPersistentReplicateRegion(Object cache, String regionName, File diskStore)
        throws Exception {
    Object store = cache.getClass().getMethod("findDiskStore", String.class).invoke(cache, "store");
    Class dataPolicyObject = Thread.currentThread().getContextClassLoader()
            .loadClass("org.apache.geode.cache.DataPolicy");
    Object dataPolicy = dataPolicyObject.getField("PERSISTENT_REPLICATE").get(null);
    if (store == null) {
        Object dsf = cache.getClass().getMethod("createDiskStoreFactory").invoke(cache);
        dsf.getClass().getMethod("setMaxOplogSize", long.class).invoke(dsf, 1L);
        dsf.getClass().getMethod("setDiskDirs", File[].class).invoke(dsf,
                new Object[] { new File[] { diskStore.getAbsoluteFile() } });
        dsf.getClass().getMethod("create", String.class).invoke(dsf, "store");
    }//from  ww  w  . j  a v  a 2s  .  c o m
    Object rf = cache.getClass().getMethod("createRegionFactory").invoke(cache);
    rf.getClass().getMethod("setDiskStoreName", String.class).invoke(rf, "store");
    rf.getClass().getMethod("setDataPolicy", dataPolicy.getClass()).invoke(rf, dataPolicy);
    rf.getClass().getMethod("create", String.class).invoke(rf, regionName);
}

From source file:com.predic8.membrane.servlet.test.ResolverTestTriggerTest.java

@Override
public Outcome handleRequest(Exchange exc) {
    try {/*  ww  w  .  j  av a  2  s.  c  om*/
        Class<?> clazz = Class.forName("com.predic8.membrane.core.resolver.ResolverTest");
        clazz.getField("deployment").set(null, "J2EE");

        Object value = router.getResolverMap().getFileSchemaResolver();
        Object resolverMap = clazz.getField("resolverMap").get(null);
        resolverMap.getClass().getMethod("addSchemaResolver", SchemaResolver.class).invoke(resolverMap, value);

        Parameterized p = new Parameterized(clazz);
        JUnitCore c = new JUnitCore();
        Result run = c.run(Request.runner(p));

        StringBuilder sb = new StringBuilder();

        sb.append(MAGIC);

        for (Failure f : run.getFailures()) {
            sb.append(f.toString());
            StringWriter stringWriter = new StringWriter();
            f.getException().printStackTrace(new PrintWriter(stringWriter));
            sb.append(stringWriter.toString());
            sb.append("\n");
            sb.append("\n");
        }

        exc.setResponse(Response.ok().header(Header.CONTENT_TYPE, MimeType.TEXT_PLAIN_UTF8).body(sb.toString())
                .build());

    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
    }
    return Outcome.RETURN;
}

From source file:com.unlockdisk.android.opengl.MainGLActivity.java

private int findSoundId(Activity activity, String variable) {
    try {/*from  w  ww .  ja v  a  2  s.c  o  m*/
        String idClass = activity.getPackageName() + ".R$raw";
        Class clazz = Class.forName(idClass);
        Field field = clazz.getField(variable);

        return field.getInt(clazz);
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.datatorrent.lib.util.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {/* www .ja v a  2s . com*/
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:org.eyeseetea.malariacare.layout.dashboard.config.DashboardSettings.java

/**
 * Resolves the value of the given attribute in the given class
 * @param generatedAndroidClass/*from   ww  w. ja va  2  s  .  c  o  m*/
 * @param attributeName
 * @return
 */
private int resolve(Class generatedAndroidClass, String attributeName) {
    try {
        Field field = generatedAndroidClass.getField(attributeName);
        return field.getInt(null);
    } catch (Exception ex) {
        return 0;
    }
}

From source file:org.openmrs.module.uiframework.UiFrameworkActivator.java

/**
 * Every time the spring context is refreshed, we make callbacks to any {@link UiContextRefreshedCallback}
 * beans that are managed by Spring. The main purpose of this is to that modules can be configured to use
 * the UI Framework through simple usage of {@link StandardModuleUiConfiguration}.
 * /*w  ww  .  j  a  v  a2s . c o m*/
 * @see org.openmrs.module.BaseModuleActivator#contextRefreshed()
 */
@Override
public void contextRefreshed() {
    contextLastRefreshedTime = System.currentTimeMillis();

    // START HACK
    // since we're not using a Listener anymore, these are not set at startup
    try {
        Class<?> webConstants1x = Context.loadClass("org.openmrs.web.WebConstants");
        String webappName = (String) webConstants1x.getField("WEBAPP_NAME").get(null);
        WebConstants.CONTEXT_PATH = webappName;
        WebConstants.WEBAPP_NAME = webappName;
    } catch (Exception ex) {
        log.error("Failed to get CONTEXT_PATH from WebConstants during UI Framework startup");
    }
    // END HACK

    PageFactory pageFactory = getComponent(PageFactory.class);
    FragmentFactory fragmentFactory = getComponent(FragmentFactory.class);
    ResourceFactory resourceFactory = getComponent(ResourceFactory.class);

    List<UiContextRefreshedCallback> callbacks = Context
            .getRegisteredComponents(UiContextRefreshedCallback.class);
    for (UiContextRefreshedCallback callback : callbacks) {
        try {
            callback.afterContextRefreshed(pageFactory, fragmentFactory, resourceFactory);
        } catch (Exception ex) {
            log.error("Error in UiContextRefreshedCallback: " + callback, ex);
        }
    }
}

From source file:fr.univ_tours.etu.nlp.CoreNLPNERTika.java

/**
 * Creates a NERecogniser by loading model from given path
 * @param modelPath path to NER model file
 *//*  w  w  w.j  a v a 2 s .  c o  m*/
public CoreNLPNERTika(String modelPath) {
    try {
        Properties props = new Properties();
        Class<?> classifierClass = Class.forName(CLASSIFIER_CLASS_NAME);
        Method loadMethod = classifierClass.getMethod("getClassifier", String.class, Properties.class);
        classifierInstance = loadMethod.invoke(classifierClass, modelPath, props);
        classifyMethod = classifierClass.getMethod("classifyToCharacterOffsets", String.class);

        //these fields are for accessing result
        Class<?> tripleClass = Class.forName("edu.stanford.nlp.util.Triple");
        this.firstField = tripleClass.getField("first");
        this.secondField = tripleClass.getField("second");
        this.thirdField = tripleClass.getField("third");
        this.available = true;
    } catch (Exception e) {
        LOG.warn("{} while trying to load the model from {}", e.getMessage(), modelPath);
    }
    LOG.info("Available for service ? {}", available);
}