Example usage for java.lang.reflect Field get

List of usage examples for java.lang.reflect Field get

Introduction

In this page you can find the example usage for java.lang.reflect Field get.

Prototype

@CallerSensitive
@ForceInline 
public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Returns the value of the field represented by this Field , on the specified object.

Usage

From source file:com.anteam.demo.codec.common.CoderUtil.java

public static Object encode(Object source, EncryptAlgorithm encryptAlgorithm, byte[] key)
        throws EncoderException {
    if (source == null || encryptAlgorithm == null) {
        return null;
    }/*from   w  w  w.  j a v  a 2s  .c o m*/
    Object result = source;
    if (source instanceof byte[]) {
        return CoderUtil.encode((byte[]) source, encryptAlgorithm, key);
    } else if (source instanceof String) {
        return CoderUtil.encode((String) source, encryptAlgorithm, key);
    }
    Field[] fields = source.getClass().getDeclaredFields();
    for (Field field : fields) {
        Encrypted encrypted = field.getAnnotation(Encrypted.class);
        if (encrypted != null) {
            ReflectionUtils.makeAccessible(field);
            if (!Modifier.isStatic(field.getModifiers())) {
                try {
                    field.set(source, CoderUtil.encode(field.get(source)));
                } catch (IllegalAccessException e) {
                    LOG.error("?:" + source.getClass().getName() + ":" + field.getName(), e);
                }
            }
        }
    }
    return result;
}

From source file:com.anteam.demo.codec.common.CoderUtil.java

public static Object decode(Object source, EncryptAlgorithm encryptAlgorithm, byte[] key)
        throws DecoderException {
    if (source == null || encryptAlgorithm == null) {
        return null;
    }//from  ww w.  j ava 2s.  c o  m
    Object result = source;
    if (source instanceof byte[]) {
        return CoderUtil.decode((byte[]) source, encryptAlgorithm, key);
    } else if (source instanceof String) {
        return CoderUtil.decode((String) source, encryptAlgorithm, key);
    }
    Field[] fields = source.getClass().getDeclaredFields();
    for (Field field : fields) {
        Encrypted encrypted = field.getAnnotation(Encrypted.class);
        if (encrypted != null) {
            ReflectionUtils.makeAccessible(field);
            if (!Modifier.isStatic(field.getModifiers())) {
                try {
                    field.set(source, CoderUtil.decode(field.get(source)));
                } catch (IllegalAccessException e) {
                    LOG.error("?:" + source.getClass().getName() + ":" + field.getName(), e);
                }
            }
        }
    }
    return result;
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Retrieves the statistics data from an Alfresco default {@code DefaultSimpleCache}
 *
 * @param defaultSimpleCache//from w  w w .ja v  a  2s  .  c  o  m
 *            the simple cache instance
 * @return the statistics object
 * @throws Exception
 *             if the reflective access fails for any reason
 */
public static Object getDefaultSimpleCacheStats(final DefaultSimpleCache<?, ?> defaultSimpleCache)
        throws Exception {
    ParameterCheck.mandatory("defaultSimpleCache", defaultSimpleCache);

    final Field googleCacheField = DefaultSimpleCache.class.getDeclaredField("cache");
    // will fail in Java 9 but no other way due to private visibility and lack of accessor
    googleCacheField.setAccessible(true);
    final Object googleCache = googleCacheField.get(defaultSimpleCache);

    final CacheStats stats = ((Cache<?, ?>) googleCache).stats();
    return stats;
}

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

public static Object getScopeService(IScope scope, Class<?> intf, Class<?> defaultClass, boolean checkHandler) {
    if (scope == null || intf == null) {
        return null;
    }/* ww  w  . ja va2s  .  c  o m*/
    // We expect an interface
    assert intf.isInterface();

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

    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've 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) {
                handler = getScopeService(scope, (String) serviceName, defaultClass);
            }
        } catch (Exception e) {
            log.debug("No string field 'BEAN_NAME' in that interface");
        }
    }
    if (handler == null && defaultClass != null) {
        try {
            handler = defaultClass.newInstance();
        } catch (Exception e) {
            log.error("", e);
        }
    }
    // cache service
    scope.setAttribute(attr, handler);
    return handler;
}

From source file:org.openflamingo.uploader.el.ELService.java

public static Object findConstant(String className, String constantName) throws SystemException {
    try {/*from   ww w .  j  a v a 2 s .  c o m*/
        Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        Field field = clazz.getField(constantName);
        if ((field.getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != (Modifier.PUBLIC
                | Modifier.STATIC)) {
            // throw new SystemException(ErrorCode.E0114, className, constantName);
        }
        return field.get(null);
    } catch (IllegalAccessException ex) {
        throw new SystemException(ex);
    } catch (NoSuchFieldException ex) {
        throw new SystemException(ex);
    } catch (ClassNotFoundException ex) {
        throw new SystemException(ex);
    }
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Retrieves the statistics data from an Alfresco Enterprise Edition {@code HazelcastSimpleCache}
 *
 * @param simpleCache//from   w w w.ja  va  2 s .  c o m
 *            the simple cache
 * @return the statistics object
 * @throws Exception
 *             if the reflective access fails for any reason
 */
public static Object getHzSimpleCacheStats(final SimpleCache<?, ?> simpleCache) throws Exception {
    ParameterCheck.mandatory("simpleCache", simpleCache);

    final Field mapField = simpleCache.getClass().getDeclaredField("map");
    // will fail in Java 9 but no other way due to private visibility, Enterprise-only class and lack of accessor
    mapField.setAccessible(true);
    final Object internalMap = mapField.get(simpleCache);
    final Method mapStatsGetter = internalMap.getClass().getMethod("getLocalMapStats");
    final Object stats = mapStatsGetter.invoke(internalMap);

    return stats;
}

From source file:activiti.common.persistence.util.ReflectHelper.java

/**
 * ?objfieldName/*from   w  ww  . ja  va  2s.  co m*/
 * 
 * @param obj
 * @param fieldName
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T getValueByFieldType(Object obj, Class<T> fieldType) {
    Object value = null;
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field[] fields = superClass.getDeclaredFields();
            for (Field f : fields) {
                if (f.getType() == fieldType) {
                    if (f.isAccessible()) {
                        value = f.get(obj);
                        break;
                    } else {
                        f.setAccessible(true);
                        value = f.get(obj);
                        f.setAccessible(false);
                        break;
                    }
                }
            }
            if (value != null) {
                break;
            }
        } catch (Exception e) {
        }
    }
    return (T) value;
}

From source file:Main.java

public static boolean equals(Object target, Object o) {
    if (target == o)
        return true;
    if (target == null || o == null)
        return false;
    if (!target.getClass().equals(o.getClass()))
        return false;

    Class<?> current = target.getClass();
    do {/*from  www.j a  v  a  2  s  .  c  o  m*/
        for (Field f : current.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())
                    || f.isSynthetic()) {
                continue;
            }

            Object self;
            Object other;
            try {
                f.setAccessible(true);
                self = f.get(target);
                other = f.get(o);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
            if (self == null) {
                if (other != null)
                    return false;
            } else if (self.getClass().isArray()) {
                if (self.getClass().equals(boolean[].class)) {
                    if (!Arrays.equals((boolean[]) self, (boolean[]) other))
                        return false;
                } else if (self.getClass().equals(char[].class)) {
                    if (!Arrays.equals((char[]) self, (char[]) other))
                        return false;
                } else if (self.getClass().equals(byte[].class)) {
                    if (!Arrays.equals((byte[]) self, (byte[]) other))
                        return false;
                } else if (self.getClass().equals(short[].class)) {
                    if (!Arrays.equals((short[]) self, (short[]) other))
                        return false;
                } else if (self.getClass().equals(int[].class)) {
                    if (!Arrays.equals((int[]) self, (int[]) other))
                        return false;
                } else if (self.getClass().equals(long[].class)) {
                    if (!Arrays.equals((long[]) self, (long[]) other))
                        return false;
                } else if (self.getClass().equals(float[].class)) {
                    if (!Arrays.equals((float[]) self, (float[]) other))
                        return false;
                } else if (self.getClass().equals(double[].class)) {
                    if (!Arrays.equals((double[]) self, (double[]) other))
                        return false;
                } else {
                    if (!Arrays.equals((Object[]) self, (Object[]) other))
                        return false;
                }
            } else if (!self.equals(other)) {
                return false;
            }
        }
        current = current.getSuperclass();
    } while (!Object.class.equals(current));

    return true;
}

From source file:com.cnksi.core.tools.utils.Reflections.java

/**
 * ?, private/protected, ??getter./*w ww.j  a  v  a 2s.  c  o  m*/
 */
public static Object getFieldValue(final Object obj, final String fieldName) {

    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }

    Object result = null;
    try {
        result = field.get(obj);
    } catch (IllegalAccessException e) {
        logger.error("??{}", e.getMessage());
    }
    return result;
}

From source file:com.google.gwt.dev.shell.tomcat.EmbeddedTomcatServer.java

/**
 * Returns what local port the Tomcat connector is running on.
 * //from   w ww .  j ava 2  s . com
 * When starting Tomcat with port 0 (i.e. choose an open port), there is just
 * no way to figure out what port it actually chose. So we're using pure
 * hackery to steal the port via reflection. The only works because we bundle
 * Tomcat with GWT and know exactly what version it is.
 */
private static int computeLocalPort(Connector connector) {
    Throwable caught = null;
    try {
        Field phField = CoyoteConnector.class.getDeclaredField("protocolHandler");
        phField.setAccessible(true);
        Object protocolHandler = phField.get(connector);

        Field epField = protocolHandler.getClass().getDeclaredField("ep");
        epField.setAccessible(true);
        Object endPoint = epField.get(protocolHandler);

        Field ssField = endPoint.getClass().getDeclaredField("serverSocket");
        ssField.setAccessible(true);
        ServerSocket serverSocket = (ServerSocket) ssField.get(endPoint);

        return serverSocket.getLocalPort();
    } catch (SecurityException e) {
        caught = e;
    } catch (NoSuchFieldException e) {
        caught = e;
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    }
    throw new RuntimeException("Failed to retrieve the startup port from Embedded Tomcat", caught);
}