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

@SuppressWarnings("unchecked")
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;//w ww. j a v  a  2 s.co m
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}

From source file:org.tros.torgo.interpreter.InterpreterThread.java

/**
 * Threaded function.//from ww w.j av a  2  s  . com
 */
@Override
public final void run() {
    listeners.fire().started();
    try {
        //walk the parse tree and build the execution map
        LexicalAnalyzer l = getLexicalAnalysis(source);

        script = l.getEntryPoint();
        InterpreterListener listener = new InterpreterListener() {

            @Override
            public void started() {
            }

            @Override
            public void finished() {
            }

            @Override
            public void error(Exception e) {
                listeners.fire().error(e);
            }

            @Override
            public void message(String msg) {
                listeners.fire().message(msg);
            }

            /**
             * Pass on the currStatement event to any listeners.
             *
             * @param block
             * @param scope
             */
            @Override
            public void currStatement(CodeBlock block, Scope scope) {
                listeners.fire().currStatement(block, scope);
            }
        };
        for (CodeBlock cb : l.getCodeBlocks()) {
            cb.addInterpreterListener(listener);
            monitor.addHaltListener(cb);
        }
        //interpret the script
        process(script);
    } catch (Exception ex) {
        listeners.fire().error(ex);
        org.tros.utils.logging.Logging.getLogFactory().getLogger(InterpreterThread.class).fatal(null, ex);
        try {
            Class<?> lc = Class.forName("org.tros.utils.logging.LogConsole");
            Field field = lc.getField("CONSOLE");
            java.lang.reflect.Method m = field.getType().getMethod("setVisible", boolean.class);
            Object fieldInstance = field.get(null);
            m.invoke(fieldInstance, true);
        } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | NoSuchMethodException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex1) {
        }
    }
    listeners.fire().finished();
}

From source file:brooklyn.management.osgi.OsgiStandaloneTest.java

protected void setAMultiplier(Bundle bundle, int newMultiplier) throws Exception {
    Assert.assertNotNull(bundle);/*  ww  w. java  2  s  .co m*/
    Class<?> aClass = bundle.loadClass("brooklyn.test.osgi.TestA");
    aClass.getField("multiplier").set(null, newMultiplier);
}

From source file:com.google.feedserver.util.CommonsCliHelper.java

/**
 * Returns help text for the given field and class.
 * /*from   w ww  .  java  2  s  .  co  m*/
 * @returns String the help text.
 */
@SuppressWarnings("unchecked")
private String getHelpText(Class flagClass, String argumentName) {
    String helpText = "None Available";
    try {
        helpText = (String) flagClass.getField(argumentName + "_HELP").get(null);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Help text must be of type String.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Help text must be public!", e);
    }
    return helpText;
}

From source file:seava.j4e.presenter.service.ServiceLocatorJee.java

@Override
public <M, F, P> IDsService<M, F, P> findDsService(Class<?> modelClass) throws Exception {
    // return this.findDsService(modelClass.getSimpleName());
    return this.findDsService((String) modelClass.getField("ALIAS").get(null));
}

From source file:org.xmlsh.util.JavaUtils.java

public static Object getFieldValue(Class<?> cls, Object instance, String fieldName, ClassLoader classloader)
        throws InvalidArgumentException, SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, ClassNotFoundException {
    assert (cls != null);
    assert (fieldName != null);

    Field f = cls.getField(fieldName);

    if (f == null)
        throw new InvalidArgumentException("No field match found for: " + cls.getName() + "." + fieldName);

    Object obj = f.get(instance == null ? null : instance);
    return obj;/*w  ww .j ava 2  s.c  o  m*/
}

From source file:org.sakaiproject.metaobj.utils.ioc.FieldRetrievingFactoryBean.java

public void afterPropertiesSet() throws ClassNotFoundException, NoSuchFieldException {
    if (this.targetClass != null && this.targetObject != null) {
        throw new IllegalArgumentException("Specify either targetClass or targetObject, not both");
    }//from w  w  w  .ja  va2s.  c  o  m

    if (this.targetClass == null && this.targetObject == null) {
        if (this.targetField != null) {
            throw new IllegalArgumentException(
                    "Specify targetClass or targetObject in combination with targetField");
        }

        // If no other property specified, consider bean name as static field expression.
        if (this.staticField == null) {
            this.staticField = this.beanName;
        }

        // try to parse static field into class and field
        int lastDotIndex = this.staticField.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == this.staticField.length()) {
            throw new IllegalArgumentException("staticField must be a fully qualified class plus method name: "
                    + "e.g. 'example.MyExampleClass.MY_EXAMPLE_FIELD'");
        }
        String className = this.staticField.substring(0, lastDotIndex);
        String fieldName = this.staticField.substring(lastDotIndex + 1);
        this.targetClass = ClassUtils.forName(className);
        this.targetField = fieldName;
    }

    else if (this.targetField == null) {
        // either targetClass or targetObject specified
        throw new IllegalArgumentException("targetField is required");
    }

    // try to get the exact method first
    Class targetClass = (this.targetObject != null) ? this.targetObject.getClass() : this.targetClass;
    this.fieldObject = targetClass.getField(this.targetField);
}

From source file:com.googlecode.ddom.weaver.inject.InjectionPlugin.java

/**
 * Add the given binding. The binding will be configured with a {@link SingletonInjector} or a
 * {@link PrototypeInjector} depending on whether the injected class is a singleton as defined
 * in the Javadoc of the {@link SingletonInjector} class.
 * //from  w w  w  . j a v a 2 s. c om
 * @param fieldType
 *            the target field type
 * @param injectedClass
 *            the injected class or <code>null</code> to inject a <code>null</code> value
 */
public <T> void addBinding(Class<T> fieldType, Class<? extends T> injectedClass) {
    Injector injector;
    if (injectedClass == null) {
        injector = null;
    } else {
        Field instanceField;
        try {
            Field candidateField = injectedClass.getField("INSTANCE");
            int modifiers = candidateField.getModifiers();
            // Note: getField only returns public fields, so no need to check for that
            // modifier here
            if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) {
                if (log.isWarnEnabled()) {
                    log.warn("Ignoring public INSTANCE field in " + injectedClass.getName()
                            + " that is not static final");
                }
                instanceField = null;
            } else if (!fieldType.isAssignableFrom(candidateField.getType())) {
                if (log.isWarnEnabled()) {
                    log.warn("Ignoring INSTANCE field of incompatible type in " + injectedClass.getName());
                }
                instanceField = null;
            } else {
                instanceField = candidateField;
            }
        } catch (NoSuchFieldException ex) {
            instanceField = null;
        }
        if (instanceField != null) {
            injector = new SingletonInjector(injectedClass.getName(), instanceField.getType().getName());
        } else {
            injector = new PrototypeInjector(injectedClass.getName());
        }
    }
    addBinding(fieldType.getName(), injector);
}

From source file:com.cerema.cloud2.ui.activity.LogHistoryActivity.java

/**
 * Start activity for sending email with logs attached
 *///from  w w w.j  av  a 2s. c  o  m
private void sendMail() {

    // For the moment we need to consider the possibility that setup.xml
    // does not include the "mail_logger" entry. This block prevents that
    // compilation fails in this case.
    String emailAddress;
    try {
        Class<?> stringClass = R.string.class;
        Field mailLoggerField = stringClass.getField("mail_logger");
        int emailAddressId = (Integer) mailLoggerField.get(null);
        emailAddress = getString(emailAddressId);
    } catch (Exception e) {
        emailAddress = "";
    }

    ArrayList<Uri> uris = new ArrayList<Uri>();

    // Convert from paths to Android friendly Parcelable Uri's
    for (String file : Log_OC.getLogFileNames()) {
        File logFile = new File(mLogPath, file);
        if (logFile.exists()) {
            uris.add(Uri.fromFile(logFile));
        }
    }

    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);

    intent.putExtra(Intent.EXTRA_EMAIL, emailAddress);
    String subject = String.format(getString(R.string.log_send_mail_subject), getString(R.string.app_name));
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType(MAIL_ATTACHMENT_TYPE);
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, getString(R.string.log_send_no_mail_app), Toast.LENGTH_LONG).show();
        Log_OC.i(TAG, "Could not find app for sending log history.");
    }

}

From source file:com.synox.android.ui.activity.LogHistoryActivity.java

/**
 * Start activity for sending email with logs attached
 *///  www .j ava2s  .  c  o  m
private void sendMail() {

    // For the moment we need to consider the possibility that setup.xml
    // does not include the "mail_logger" entry. This block prevents that
    // compilation fails in this case.
    String emailAddress;
    try {
        Class<?> stringClass = R.string.class;
        Field mailLoggerField = stringClass.getField("mail_logger");
        int emailAddressId = (Integer) mailLoggerField.get(null);
        emailAddress = getString(emailAddressId);
    } catch (Exception e) {
        emailAddress = "";
    }

    ArrayList<Uri> uris = new ArrayList<>();

    // Convert from paths to Android friendly Parcelable Uri's
    for (String file : Log_OC.getLogFileNames()) {
        File logFile = new File(mLogPath, file);
        if (logFile.exists()) {
            uris.add(Uri.fromFile(logFile));
        }
    }

    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);

    intent.putExtra(Intent.EXTRA_EMAIL, emailAddress);
    String subject = String.format(getString(R.string.log_send_mail_subject), getString(R.string.app_name));
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType(MAIL_ATTACHMENT_TYPE);
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, getString(R.string.log_send_no_mail_app), Toast.LENGTH_LONG).show();
        Log_OC.i(TAG, "Could not find app for sending log history.");
    }

}