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:com.cognifide.qa.bb.aem.touch.pageobjects.pages.AuthorPage.java

/**
 * Looks for css class of given component class and return its content.
 *
 * @param component component class.//  w w  w.j  a va 2 s .  com
 * @return content of component.
 */
public <T> T getContent(Class<T> component) {
    Objects.requireNonNull(component, "clazz property was not specified in YAML config");
    globalBar.switchToPreviewMode();
    frameSwitcher.switchTo(CONTENT_FRAME);
    WebElement scope = null;
    try {
        String selector = (String) component.getField("CSS").get(null);
        scope = driver.findElement(By.cssSelector(selector));
    } catch (IllegalAccessException e) {
        LOG.error("CSS was not accessible, injecting with default scope", e);
    } catch (NoSuchFieldException e) {
        LOG.error("CSS field was not present in the page object, injecting with default scope", e);
    }
    frameSwitcher.switchBack();
    return scope == null ? pageObjectInjector.inject(component, CONTENT_FRAME)
            : pageObjectInjector.inject(component, scope, CONTENT_FRAME);
}

From source file:org.jboss.dashboard.database.hibernate.LOBHelper.java

public void oracleNullSafeSet(PreparedStatement statement, Object value, int index, ValueWriter vw)
        throws HibernateException, SQLException {
    try {//from www  .  j a  v a2s .  c  o  m
        // Invoke by reflection the Oracle classes
        Class oracleBlobClass = Class.forName(ORACLE_CLASS);

        Method createTempMethod = getMethod(oracleBlobClass, ORACLE_TEMP_METHOD, Connection.class, Boolean.TYPE,
                Integer.TYPE);

        Field durationSession = oracleBlobClass.getField(ORACLE_DURATION__SESSION);
        Object arglist[] = new Object[3];
        Connection conn = statement.getConnection();
        arglist[0] = conn;
        arglist[1] = Boolean.TRUE;
        arglist[2] = durationSession.get(null);

        Object tempBlob = null;

        // Needed to avoid JBoss AS class loading issues...
        Class connClassInCurrentClassLoader = Class.forName(conn.getClass().getName());

        // Direct Oracle connection
        if (Class.forName(ORACLE_JDBC_ORACLE_CONNECTION).isAssignableFrom(connClassInCurrentClassLoader)) {
            tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method
        }
        // JBoss AS data source wrapper connection.
        else if (WrappedConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) {
            arglist[0] = ReflectionUtils.invokeMethod(conn, "getUnderlyingConnection", null);
            tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method
        }
        // C3P0 pool managed connection.
        else if (NewProxyConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) {
            NewProxyConnection castCon = (NewProxyConnection) conn;
            arglist[0] = C3P0ProxyConnection.RAW_CONNECTION;
            tempBlob = castCon.rawConnectionOperation(createTempMethod, C3P0ProxyConnection.RAW_CONNECTION,
                    arglist);
        }
        // Apache's DBCP pool managed connection.
        else if (PoolableConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) {
            arglist[0] = ((PoolableConnection) statement.getConnection()).getDelegate();
            tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method

        } else {

            boolean throwException = true;
            //check if we are running in websphere
            try {
                String wasConnectionWrapper = "com.ibm.ws.rsadapter.jdbc.WSJdbcConnection";
                Class wasConnectionWrapperClass = Class.forName(wasConnectionWrapper);

                if (wasConnectionWrapperClass.isAssignableFrom(connClassInCurrentClassLoader)) {

                    String helperClass = "com.ibm.websphere.rsadapter.WSCallHelper";
                    Class helper = Class.forName(helperClass);

                    Method nativeConnMethod = helper.getMethod("getNativeConnection",
                            new Class[] { Object.class });

                    Connection nativeConn = (Connection) nativeConnMethod.invoke(null, conn);

                    if (Class.forName(ORACLE_JDBC_ORACLE_CONNECTION).isAssignableFrom(nativeConn.getClass())) {

                        arglist[0] = nativeConn;
                        tempBlob = createTempMethod.invoke(null, arglist);
                        throwException = false;
                    }
                }

            } catch (Throwable e) {
                e.printStackTrace();
                // do nothing
            }
            if (throwException) {
                throw new HibernateException("JDBC connection object must be a oracle.jdbc.OracleConnection "
                        + "a " + WrappedConnection.class.getName() + "a " + PoolableConnection.class.getName()
                        + "or a " + NewProxyConnection.class.getName() + ". Connection class is "
                        + connClassInCurrentClassLoader.getName());
            }
        }

        Method openMethod = getMethod(oracleBlobClass, ORACLE_OPEN_METHOD, Integer.TYPE, null, null);

        Field fieldReadWrite = oracleBlobClass.getField(ORACLE_MODE__READWRITE);
        arglist = new Object[1];
        arglist[0] = fieldReadWrite.get(null); //null is valid because of static field

        openMethod.invoke(tempBlob, arglist);

        Method getOutputStreamMethod = oracleBlobClass.getDeclaredMethod(ORACLE_GET_BINARY_OUTPUT_STREAM, null);

        OutputStream os = (OutputStream) getOutputStreamMethod.invoke(tempBlob, null);

        try {
            vw.writeValue(os, value);
            os.flush();
        } finally {
            os.close();
        }

        Method closeMethod = oracleBlobClass.getDeclaredMethod(ORACLE_CLOSE, null);

        closeMethod.invoke(tempBlob, null);

        statement.setBlob(index, (Blob) tempBlob);
    } catch (Exception e) {
        throw new HibernateException("Error in oracleNullSafeSet", e);
    }
}

From source file:main.java.org.ros.robot.SensorListener.java

@SuppressWarnings("rawtypes")
public void publishData(SensorData message) {
    // so go through and publish data based on names
    Class theMessage = message.getClass();
    Field messField;//www.  j  a  v a 2s .  com
    Set<String> keys = publisher.keySet();
    Iterator<String> itr = keys.iterator();
    while (itr.hasNext()) {
        String fieldName = itr.next();
        try {
            // get the field name
            messField = theMessage.getField(fieldName);
            // get the current time for the time stamps
            //Time timeStamp = node.getCurrentTime();

            if (fieldName.contains("infrared")) {
                // get the field data
                float rangeData = (Float) messField.get(message);

                pubRange.get(fieldName).range = (float) (rangeData * .01);

                // I am using secs in the header to be the key
                // since timestamp secs couldn't keep up (neither could nsecs)
                // I define my own secs in terms of when it leaves here
                pubRange.get(fieldName).header.stamp.secs = (int) count;
                // now publish it!
                publisher.get(fieldName).publish(pubRange.get(fieldName));
            } else if (fieldName.contains("ultrasonic")) {
                // get field data
                // must do this because java doesn't have unsigned bytes...
                int rangeData = ((Byte) messField.get(message)) & 0xff;

                log.debug(rangeData);

                pubRange.get(fieldName).range = (float) ((float) rangeData * .01);

                // I am using secs in the header to be the key
                // since timestamp secs couldn't keep up (neither could nsecs)
                // I define my own secs in terms of when it leaves here
                pubRange.get(fieldName).header.stamp.secs = (int) count;
                publisher.get(fieldName).publish(pubRange.get(fieldName));
            } else if (fieldName.contains("human")) {
                // this outputs the human data as range messages

                // get the range
                int rangeData = (Integer) messField.get(message);

                // put in the data

                pubRange.get(fieldName).range = (float) rangeData;

                // I am using secs in the header to be the key
                // since timestamp secs couldn't keep up (neither could nsecs)
                // I define my own secs in terms of when it leaves here
                pubRange.get(fieldName).header.stamp.secs = (int) count;

                //log.info("Recieved Message from " + fieldName + " range is " + pubRange.range);

                publisher.get(fieldName).publish(pubRange.get(fieldName));

            }

        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

From source file:com.onesignal.OneSignalUnityProxy.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public OneSignalUnityProxy(String listenerName, String googleProjectNumber, String oneSignalAppId, int logLevel,
        int visualLogLevel) {
    unityListenerName = listenerName;/*from ww  w  .  j ava2  s .co  m*/

    try {
        // We use reflection here so the default proguard config does not get an error for native apps.
        Class unityPlayerClass;
        unityPlayerClass = Class.forName("com.unity3d.player.UnityPlayer");
        unitySendMessage = unityPlayerClass.getMethod("UnitySendMessage", String.class, String.class,
                String.class);

        OneSignal.sdkType = "unity";
        OneSignal.setLogLevel(logLevel, visualLogLevel);
        OneSignal.init((Activity) unityPlayerClass.getField("currentActivity").get(null), googleProjectNumber,
                oneSignalAppId, this);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:nu.staldal.lsp.wrapper.ReadonlyBeanMap.java

private Member tryToLookupMember(final String property, final String... prefixes) {
    final Class<? extends Object> beanClass = bean.getClass();

    for (final String prefix : prefixes) {
        try {/*  www.  jav a2 s  .c om*/
            final String methodName = prefix + StringUtils.capitalize(property);
            return beanClass.getMethod(methodName);
        } catch (NoSuchMethodException ignored) {
        }
    }

    try {
        return beanClass.getField(property);
    } catch (NoSuchFieldException ignored) {
    }

    try {
        return beanClass.getMethod(property);
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:org.mandarax.dsl.util.DefaultResolver.java

@Override
public Member getMember(Context context, String name, String className, String... paramTypeNames)
        throws ResolverException {
    Class clazz = getType(context, className);
    boolean isFieldRef = paramTypeNames == null;
    if (isFieldRef) {
        Field field = null;/*w ww . j  a v  a  2 s  .  co  m*/
        try {
            field = clazz.getField(name);
        } catch (Exception e) {
            // LOGGER.error(e);
        }
        if (field != null && Modifier.isPublic(field.getModifiers())) {
            LOGGER.debug("Resolving feature " + name + " in " + className + " with parameters " + paramTypeNames
                    + " to " + field);
            return field;
        }

        // try to use bean framework
        Exception x = null;
        try {
            PropertyDescriptor[] properties = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
            for (PropertyDescriptor p : properties) {
                if (p.getName().equals(name)) {
                    Method reader = p.getReadMethod();
                    if (reader != null) {
                        LOGGER.debug("Resolving feature " + name + " in " + className + " with parameters "
                                + paramTypeNames + " to " + reader);
                        return reader;
                    } else {
                        break;
                    }
                }
            }
        } catch (IntrospectionException e) {
            x = e;
        }
        // try to locate method with exact name: this will map property hasWife to method hasWife() instead of getHasWife()
        try {
            @SuppressWarnings("unchecked")
            Method m = clazz.getMethod(name, new Class[] {});
            if (m != null && Modifier.isPublic(m.getModifiers())) {
                LOGGER.debug("Resolving feature " + name + " in " + className + " with parameters "
                        + paramTypeNames + " to " + m);
                return m;
            }
        } catch (Exception e2) {
            x = e2;
        }

        throw new ResolverException("Cannot resolve property " + name + " in " + clazz.getName(), x);
    }

    // method access
    Class[] paramTypes = new Class[paramTypeNames.length];
    for (int i = 0; i < paramTypeNames.length; i++) {
        paramTypes[i] = getType(context, paramTypeNames[i]);
    }

    try {
        Method m = MethodUtils.getMatchingAccessibleMethod(clazz, name, paramTypes);
        if (Modifier.isPublic(m.getModifiers())) {
            LOGGER.debug("Resolving feature " + name + " in " + className + " with parameters " + paramTypeNames
                    + " to " + m);
            return m;
        } else {
            throw new ResolverException("Method " + m + " in " + clazz.getName() + " is not visible");
        }
    } catch (Exception e) {
        throw new ResolverException("Cannot resolve method " + name + " in " + clazz.getName(), e);
    }

}

From source file:org.omnaest.utils.reflection.ReflectionUtils.java

/**
 * Determines the index position of a declared {@link Field} within a given {@link Class}.
 * /*from  w  ww .j a  v  a  2  s . c  o  m*/
 * @param clazz
 * @param fieldname
 * @return -1 if the {@link Field} could not be determined at all.
 */
public static int declaredFieldIndexPosition(Class<?> clazz, String fieldname) {
    //
    int retval = -1;

    //
    if (clazz != null && fieldname != null) {
        //
        try {
            //
            Field field = clazz.getField(fieldname);

            //
            if (field != null) {
                //
                Field[] declaredFields = clazz.getDeclaredFields();
                if (declaredFields != null) {
                    retval = ArrayUtils.indexOf(declaredFields, field);
                }
            }
        } catch (Exception e) {
        }
    }

    //
    return retval;
}

From source file:com.googlecode.ehcache.annotations.config.AnnotationDrivenEhCacheBeanDefinitionParser.java

/**
 * Utility API used to setup each of the default {@link CacheKeyGenerator} implementations. Requires
 * that the class has a static String field named DEFAULT_BEAN_NAME declared that is used for the bean
 * name. //from w  w w.  jav a  2s.c om
 */
protected final void setupDefaultCacheKeyGenerator(
        Class<? extends CacheKeyGenerator<? extends Serializable>> generatorClass, ParserContext parserContext,
        Object elementSource) {
    final String generatorName;
    try {
        final Field field = generatorClass.getField("DEFAULT_BEAN_NAME");
        generatorName = (String) field.get(null);
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not access static field 'DEFAULT_BEAN_NAME' on "
                + generatorClass + ". This field is required to be setup as a default CacheKeyGenerator", e);
    }

    final RootBeanDefinition defaultKeyGenerator = new RootBeanDefinition(generatorClass);
    defaultKeyGenerator.setSource(elementSource);
    defaultKeyGenerator.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

    if (ReflectionHelperAware.class.isAssignableFrom(generatorClass)) {
        final RuntimeBeanReference cacheManagerReference = new RuntimeBeanReference(
                CACHING_REFLECTION_HELPER_BEAN_NAME);

        final MutablePropertyValues propertyValues = defaultKeyGenerator.getPropertyValues();
        propertyValues.addPropertyValue("reflectionHelper", cacheManagerReference);
    }

    final BeanDefinitionRegistry registry = parserContext.getRegistry();
    registry.registerBeanDefinition(generatorName, defaultKeyGenerator);
}

From source file:de.azapps.mirakel.model.query_builder.MirakelQueryBuilder.java

private <T> Uri setupQueryBuilder(final Class<T> clazz) {
    final Uri uri;
    try {/*from  w  ww . ja v  a2s. c  om*/
        uri = (Uri) clazz.getField("URI").get(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        Log.wtf(TAG, "go and implement a URI  for" + clazz.getCanonicalName());
        throw new IllegalArgumentException("go and implement a URI for " + clazz.getCanonicalName(), e);
    }
    if (this.projection.isEmpty()) {
        try {
            // can be null, because field should be static
            this.projection = Arrays.asList((String[]) clazz.getField("allColumns").get(null));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            Log.wtf(TAG, "go and implement allColumns for " + clazz.getCanonicalName());
            throw new IllegalArgumentException("go and implement allColumns for " + clazz.getCanonicalName(),
                    e);
        }
    }
    return uri;
}

From source file:org.red5.server.api.ScopeUtils.java

public static Object getScopeService(IScope scope, Class intf, Class defaultClass, boolean checkHandler) {
    if (scope == null || intf == null) {
        return null;
    }// w  ww  . jav  a 2 s .co  m
    // We expect an interface
    assert intf.isInterface();

    if (scope.hasAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName())) {
        // Return cached service
        return scope
                .getAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName());
    }

    Object handler = null;
    if (checkHandler) {
        IScope current = scope;
        while (current != null) {
            IScopeHandler scopeHandler = current.getHandler();
            if (intf.isInstance(scopeHandler)) {
                handler = scopeHandler;
                break;
            }

            if (!current.hasParent())
                break;

            current = current.getParent();
        }
    }

    if (handler == null && IScopeService.class.isAssignableFrom(intf)) {
        // We got an IScopeService, try to lookup bean
        Field key = null;
        Object serviceName = null;
        try {
            key = intf.getField("BEAN_NAME");
            serviceName = key.get(null);
            if (!(serviceName instanceof String))
                serviceName = null;
        } catch (Exception e) {
            log.debug("No string field 'BEAN_NAME' in that interface");
        }

        if (serviceName != null)
            handler = getScopeService(scope, (String) serviceName, defaultClass);
    }

    if (handler == null && defaultClass != null) {
        try {
            handler = defaultClass.newInstance();
        } catch (Exception e) {
            log.error(e);
        }
    }

    // Cache service
    scope.setAttribute(IPersistable.TRANSIENT_PREFIX + SERVICE_CACHE_PREFIX + intf.getCanonicalName(), handler);
    return handler;
}