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.alibaba.druid.pool.bonecp.TestPSCache.java

public static MockPreparedStatement unwrap(PreparedStatement stmt) throws Exception {
    if (stmt instanceof NewProxyPreparedStatement) {
        Field field = NewProxyPreparedStatement.class.getDeclaredField("inner");
        field.setAccessible(true);/*from www . j av  a2 s.  c o m*/
        return (MockPreparedStatement) field.get(stmt);
    }
    MockPreparedStatement mockStmt = stmt.unwrap(MockPreparedStatement.class);
    return mockStmt;
}

From source file:jin.collection.util.PropertyUtil.java

static Object getPropertyByField(final Object element, final String property) {
    try {//from w  w  w . java  2 s. c o  m
        final Field declaredField = element.getClass().getDeclaredField(property);
        declaredField.setAccessible(true);
        return declaredField.get(element);
    } catch (final Exception e) {
        throw new RuntimeException("", e);
    }
}

From source file:net.minecraftforge.fml.relauncher.ReflectionHelper.java

@SuppressWarnings("unchecked")
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, @Nullable E instance, int fieldIndex) {
    try {//  ww w .  j av a 2  s.c  o m
        Field f = classToAccess.getDeclaredFields()[fieldIndex];
        f.setAccessible(true);
        return (T) f.get(instance);
    } catch (Exception e) {
        throw new UnableToAccessFieldException(new String[0], e);
    }
}

From source file:Main.java

private static boolean equalFields(Object paramObject1, Object paramObject2) {
    boolean bool1 = false;
    Field[] arrayOfField1 = paramObject1.getClass().getDeclaredFields();
    Field[] arrayOfField2 = paramObject2.getClass().getDeclaredFields();
    if (arrayOfField1.length != arrayOfField2.length) {
        return bool1;
    }//  ww w.j  ava 2s. c  o m

    int i = 0;
    try {
        while (true) {
            if (i >= arrayOfField1.length)
                break;
            Field localField1 = arrayOfField1[i];
            localField1.setAccessible(true);
            Field localField2 = arrayOfField2[i];
            localField2.setAccessible(true);
            Object localObject1 = localField1.get(paramObject1);
            Object localObject2 = localField2.get(paramObject2);
            if ((localObject1 == null) && (localObject2 != null))
                break;
            if (localObject1 != null) {
                boolean bool2 = localObject1.equals(localObject2);
                if (!bool2)
                    break;
            }
            i++;
        }
    } catch (IllegalArgumentException localIllegalArgumentException) {
        localIllegalArgumentException.printStackTrace();
        bool1 = true;
    } catch (IllegalAccessException localIllegalAccessException) {
        label122: localIllegalAccessException.printStackTrace();
    }

    return bool1;
}

From source file:net.sf.beanlib.hibernate3.Hibernate3SequenceGenerator.java

/** Returns the next sequence id from the specified sequence and session. */
public static long nextval(final String sequenceName, final Session session) {
    Object target = session;/*from w w w  . j a  v  a  2 s  . c  om*/

    if (Proxy.isProxyClass(session.getClass())) {
        // Dig out the underlying session.
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(session);

        if (invocationHandler instanceof DtoCentricCloseSuppressingInvocationHandler) {
            // This is faster for we don't need to use reflection.
            DtoCentricCloseSuppressingInvocationHandler dch = (DtoCentricCloseSuppressingInvocationHandler) invocationHandler;
            target = dch.getTarget();
        } else {
            Class<?> invocationHandlerClass = invocationHandler.getClass();
            Class<?> invocationHandlerDeclaringClass = invocationHandlerClass.getDeclaringClass();

            if (invocationHandlerDeclaringClass == HibernateTemplate.class) {
                String className = invocationHandlerClass.getName();

                if (className.endsWith("CloseSuppressingInvocationHandler")) {
                    // Assume this is the private class org.springframework.orm.hibernate3.HibernateTempate$CloseSuppressingInvocationHandler
                    // Dig out the private target.  
                    // I know this is bad, but there doesn't seem to be a better way.  Oh well.
                    try {
                        Field f = invocationHandlerClass.getDeclaredField("target");
                        f.setAccessible(true);
                        target = f.get(invocationHandler);
                    } catch (SecurityException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }

                }
            }

        }
    }
    SessionImpl sessionImpl;

    if (target instanceof SessionImpl)
        sessionImpl = (SessionImpl) target;
    else
        throw new IllegalStateException("Not yet know how to handle the given session!");
    IdentifierGenerator idGenerator = createIdentifierGenerator(sequenceName, session);
    Serializable id = idGenerator.generate(sessionImpl, null);
    return (Long) id;
}

From source file:Main.java

public static boolean creteEntity(Object entity, String fileName) {
    boolean flag = false;
    try {//from  w  w w .  j  a  va2 s .c o m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fileName);

        Class clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Node EntityElement = document.getElementsByTagName(clazz.getSimpleName() + "s").item(0);

        Element newEntity = document.createElement(clazz.getSimpleName());
        EntityElement.appendChild(newEntity);

        for (Field field : fields) {
            field.setAccessible(true);
            Element element = document.createElement(field.getName());
            element.appendChild(document.createTextNode(field.get(entity).toString()));
            newEntity.appendChild(element);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(fileName));
        transformer.transform(domSource, streamResult);
        flag = true;
    } catch (ParserConfigurationException pce) {
        System.out.println(pce.getLocalizedMessage());
        pce.printStackTrace();
    } catch (TransformerException te) {
        System.out.println(te.getLocalizedMessage());
        te.printStackTrace();
    } catch (IOException ioe) {
        System.out.println(ioe.getLocalizedMessage());
        ioe.printStackTrace();
    } catch (SAXException sae) {
        System.out.println(sae.getLocalizedMessage());
        sae.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return flag;
}

From source file:Main.java

public static int getStatusBarHeight(Context context) {
    Class c = null;/*w  w  w . ja  v  a 2s  .  co  m*/
    Object bj = null;
    Field field = null;
    int x = 0, statusBarHeight = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        bj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(bj).toString());
        statusBarHeight = context.getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return statusBarHeight;
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * Convenience method that checks if the specified property is included among the allowed
 * missing properties of the given resource class via reflection
 * /*from  www . j  a va 2s  .  c o  m*/
 * @param clazz
 * @param fieldName
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@SuppressWarnings("rawtypes")
private static boolean isallowedMissingProperty(Class resourceClass, String propName)
        throws IllegalArgumentException, IllegalAccessException, InstantiationException {
    List<Field> fields = Reflect.getAllFields(resourceClass);
    if (CollectionUtils.isNotEmpty(fields)) {
        for (Field field : fields) {
            if (field.getName().equals("allowedMissingProperties"))
                return ((Set) field.get(resourceClass.newInstance())).contains(propName);
        }
    }
    return false;
}

From source file:com.feilong.core.lang.reflect.FieldUtilTemp.java

/**
 *  <code>ownerClass</code>  <code>fieldName</code> .
 *
 * @param <T>/*from ww  w  .j a  v a  2  s. c o  m*/
 *            the generic type
 * @param ownerClass
 *            the owner class
 * @param fieldName
 *            the field name
 * @param ownerObj
 *            object from which the represented field's value is to be extracted
 * @return the class field value
 * @see org.apache.commons.lang3.reflect.FieldUtils#getField(Class, String, boolean)
 * @since 1.7.1
 */
@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Class<?> ownerClass, String fieldName, Object ownerObj) {
    try {
        //?, ? Class#getField(String), ?? public
        Field field = FieldUtils.getField(ownerClass, fieldName, true);
        return (T) field.get(ownerObj);
    } catch (Exception e) {
        String message = Slf4jUtil.format("ownerClass:[{}],fieldName:[{}],ownerObj:[{}]", ownerClass.getName(),
                fieldName, ownerObj);
        LOGGER.error(message, e);
        throw new ReflectException(message, e);
    }
}

From source file:com.pinterest.deployservice.common.ChangeFeedJob.java

private static String toStringRepresentation(Object object) throws IllegalAccessException {
    if (object == null) {
        return "None";
    }//  w w  w. j a va  2 s  . c o m

    if (object instanceof List) {
        List<?> list = (List<?>) object;
        if (list.isEmpty()) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder("[");
        for (Object element : list) {
            sb.append(toStringRepresentation(element));
            sb.append(", ");
        }

        sb.delete(sb.length() - 2, sb.length());
        sb.append(']');
        return sb.toString();
    }

    Field[] fields = object.getClass().getDeclaredFields();
    if (fields.length == 0) {
        return "{}";
    }

    StringBuilder sb = new StringBuilder("{");
    for (Field field : fields) {
        field.setAccessible(true);
        Object fieldItem = field.get(object);
        sb.append(field.getName());
        sb.append(":");
        sb.append(fieldItem);
        sb.append(", ");
    }

    sb.delete(sb.length() - 2, sb.length());
    sb.append('}');
    return sb.toString();
}