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:FindField.java

int intFieldValue(Object o, String name) throws NoSuchFieldException, IllegalAccessException {
    Class c = o.getClass();
    Field fld = c.getField(name);
    int value = fld.getInt(o);
    return value;
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Send a mail message using a JNDI resource.<br>
 * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the
 * MailSessionFactory offered to payloads, making it accessible also to the engine.
 * /*  ww  w .j av a 2s  .  c o m*/
 * @param to
 * @param subject
 * @param body
 * @param mailSessionJndiAlias
 * @throws MessagingException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias)
        throws MessagingException {
    jqmlogger.debug("sending mail to " + to + " - subject is " + subject);
    ClassLoader extLoader = getExtClassLoader();
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Object mailSession = null;

    try {
        mailSession = InitialContext.doLookup(mailSessionJndiAlias);
    } catch (NamingException e) {
        throw new MessagingException("could not find mail session description", e);
    }

    try {
        Thread.currentThread().setContextClassLoader(extLoader);
        Class transportZ = extLoader.loadClass("javax.mail.Transport");
        Class sessionZ = extLoader.loadClass("javax.mail.Session");
        Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage");
        Class messageZ = extLoader.loadClass("javax.mail.Message");
        Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType");
        Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession);

        mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg,
                recipientTypeZ.getField("TO").get(null), to);
        mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject);
        mimeMessageZ.getMethod("setText", String.class).invoke(msg, body);

        transportZ.getMethod("send", messageZ).invoke(null, msg);
        jqmlogger.trace("Mail was sent");
    } catch (Exception e) {
        throw new MessagingException("an exception occurred during mail sending", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * @param cls the class to search the main in.
 * @param args command line args for the main class invoked.
 * @param useGUI <code>true</code> if the {@link GenericGUI} should be launched.
 * @return <code>true</code> if the class contains a <code>static main(String[])</code> that was invoked,
 *         <code>false</code> otherwise.
 * @see GenericGUI//from w ww. j a  v  a2  s.  c om
 */
private static boolean tryInvokeMain(Class<?> cls, String[] args, boolean useGUI) {
    try {
        if (useGUI) {
            @SuppressWarnings("unchecked")
            Class<SOMToolboxApp> sta = (Class<SOMToolboxApp>) cls;
            new GenericGUI(sta, args).setVisible(true);
            return true;
        }
    } catch (ClassCastException cce) {
        // Nop, continue...
    }

    try {
        Method main = cls.getMethod("main", String[].class);

        // special handling - if the parameter "--help" is present, also print the description
        if (ArrayUtils.contains(args, "--help")) {
            Object description = null;
            try { // try to get the LONG_DESCRIPTION field
                description = cls.getField("LONG_DESCRIPTION").get(null) + "\n";
            } catch (Exception e) {
                try { // fall back using the DESCRIPTION field
                    description = cls.getField("DESCRIPTION").get(null) + "\n";
                } catch (Exception e1) { // nothing found => write nothing...
                    description = "";
                }
            }
            System.out.println(description);
            try {
                Parameter[] options = (Parameter[]) cls.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                JSAPResult jsapResult = OptionFactory.parseResults(args, jsap, cls.getName());
                AbstractOptionFactory.printUsage(jsap, cls.getName(), jsapResult, null);
                return true;
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }
        }

        main.invoke(null, new Object[] { args });
        return true;
    } catch (InvocationTargetException e) {
        // If main throws an error, print it
        e.getCause().printStackTrace();
        return true;
    } catch (Exception e) {
        // Everything else is hidden...
        return false;
    }
}

From source file:org.apache.axis.encoding.FieldTarget.java

public FieldTarget(Object targetObject, String fieldName) throws NoSuchFieldException {
    Class cls = targetObject.getClass();
    targetField = cls.getField(fieldName);
    this.targetObject = targetObject;
}

From source file:com.espertech.esper.event.bean.TestReflectionPropFieldGetter.java

private ReflectionPropFieldGetter makeGetter(Class clazz, String fieldName) throws Exception {
    Field field = clazz.getField(fieldName);
    ReflectionPropFieldGetter getter = new ReflectionPropFieldGetter(field,
            SupportEventAdapterService.getService());
    return getter;
}

From source file:org.apache.isis.core.commons.exceptions.ExceptionUtils.java

/**
 * <p>Checks whether this <code>Throwable</code> class can store a cause.</p>
 *
 * <p>This method does <b>not</b> check whether it actually does store a cause.<p>
 *
 * @param throwable  the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0//  w  w  w  .j ava 2s  . c  om
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    /*if (throwable instanceof Nestable) {
    return true;
    } else*/ if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class cls = throwable.getClass();
    synchronized (CAUSE_METHOD_NAMES) {
        for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
            try {
                Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], null);
                if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                    return true;
                }
            } catch (NoSuchMethodException ignored) {
                // exception ignored
            } catch (SecurityException ignored) {
                // exception ignored
            }
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
        // exception ignored
    } catch (SecurityException ignored) {
        // exception ignored
    }

    return false;
}

From source file:com.tugo.dt.PojoUtils.java

/**
 * Return the getter expression for the given field.
 * <p>//from ww w.  j a  v  a  2s .  c  om
 * 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 an {}. 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 an {}. Proceeding to locate another getter method.",
                pojoClass, methodName, method.getReturnType(), exprClass);
    } catch (NoSuchMethodException ex) {
        logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass,
                methodName);
    } catch (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 an {}. Proceeding with the original expression {}.",
                pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression);
    } catch (NoSuchMethodException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    }

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

From source file:com.liferay.util.lang.StaticFieldGetter.java

public Object getFieldValue(String className, String fieldName) {
    Object obj = null;/*from  w  w  w . j  ava  2  s .  c o m*/

    try {
        Class objClass = Class.forName(className);

        Field field = objClass.getField(fieldName);

        obj = field.get(objClass);
    } catch (Exception e) {
        _log.error(e);
    }

    return obj;
}

From source file:com.tugo.dt.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 {/* w  w  w.jav  a  2s  .c om*/
        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 (org.apache.commons.lang.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.apache.geode.cache.lucene.LuceneSearchWithRollingUpgradeDUnit.java

public static void createPersistentPartitonedRegion(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_PARTITION").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");
    }//  w  ww .  jav a2  s.  co 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);
}