Example usage for java.lang.reflect Field setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:Main.java

/**
 * getChildObjs/*from w w  w.  ja va  2s . c om*/
 *
 * @param object the obj to save to db ,this object contains the property private List<Child> children;
 * @return the List<Child> value
 */
public static List<List> getChildObjs(Object object) {
    Field[] fields = object.getClass().getDeclaredFields();
    List<List> result = new ArrayList<>();
    for (Field field : fields) {
        if ("java.util.List".equals(field.getType().getName())) {
            List list = null;
            try {
                field.setAccessible(true);
                list = (List) field.get(object);
                result.add(list);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Main.java

/**
 * set attribute is accessible/*from  w  w  w  . ja va 2  s .c o  m*/
 * 
 * @param field {@link java.lang.reflect.Field}
 */
public static void makeAccessible(final Field field) {
    if (!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
        field.setAccessible(true);
    }
}

From source file:com.alibaba.druid.pool.bonecp.TestLRU.java

public static MockConnection unwrap(Connection conn) throws Exception {
    if (conn instanceof ConnectionHandle) {
        ConnectionHandle handle = (ConnectionHandle) conn;
        return (MockConnection) handle.getInternalConnection();
    }//from  ww w.  j av a  2  s. co m
    if (conn instanceof NewProxyConnection) {
        NewProxyConnection handle = (NewProxyConnection) conn;

        Field field = NewProxyConnection.class.getDeclaredField("inner");
        field.setAccessible(true);
        return (MockConnection) field.get(handle);
    }

    return conn.unwrap(MockConnection.class);
}

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);
        return (MockPreparedStatement) field.get(stmt);
    }/*w  ww .ja v a 2 s. c  om*/
    MockPreparedStatement mockStmt = stmt.unwrap(MockPreparedStatement.class);
    return mockStmt;
}

From source file:com.github.jknack.handlebars.helper.DefaultFilterHelper.java

private static <T> String getFieldValue(T input, String fielName) {
    String typeVal = "";
    try {//from  ww w.  jav  a2s  .c  o m
        Class<T> clazz = (Class<T>) input.getClass();
        Field field = clazz.getDeclaredField(fielName);
        field.setAccessible(true);
        typeVal = (String) field.get(input);
    } catch (Exception ex) {

    }
    return typeVal;
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();//from  www. j  a  v  a  2s .c  o  m
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:cz.cuni.mff.d3s.spl.example.newton.app.Main.java

private static void inspectClass(Object obj) {
    if (!INSPECT) {
        return;/* w  ww. j  a v  a  2s .co  m*/
    }

    System.out.printf("Inspecting %s:\n", obj);
    Class<?> klass = obj.getClass();
    System.out.printf("  Class: %s\n", klass.getName());
    for (Field f : klass.getDeclaredFields()) {
        Object value;
        boolean accessible = f.isAccessible();
        try {
            f.setAccessible(true);
            value = f.get(obj);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            value = String.format("<failed to read: %s>", e.getMessage());
        }
        f.setAccessible(accessible);
        System.out.printf("  Field %s: %s\n", f.getName(), value);
    }
    for (Method m : klass.getDeclaredMethods()) {
        System.out.printf("  Method %s\n", m.getName());
    }
    System.out.printf("-------\n");
    System.out.flush();
}

From source file:edu.teco.smartlambda.container.docker.HttpHijackingWorkaround.java

/**
 * Recursively traverse a hierarchy of fields in classes, obtain their value and continue the traversing on the optained object
 *
 * @param fieldContent     current object to operate on
 * @param classFieldTupels the class/field hierarchy
 *
 * @return the content of the leaf in the traversed hierarchy path
 *//*from  w ww .  j a  v  a  2  s .  c  om*/
@SneakyThrows // since the expressions are constant the exceptions cannot occur (except when the library is changed, but then a crash
// is favourable)
private static Object getInternalField(final Object fieldContent, final List<String[]> classFieldTupels) {
    Object curr = fieldContent;
    for (final String[] classFieldTuple : classFieldTupels) {
        //noinspection ConstantConditions
        final Field field = Class.forName(classFieldTuple[0]).getDeclaredField(classFieldTuple[1]);
        field.setAccessible(true);
        curr = field.get(curr);
    }
    return curr;
}

From source file:api_proto3.TestElf.java

public static boolean getConnectionCommitDirtyState(Connection connection) {
    try {/*from w ww .  j a  va  2 s.c om*/
        Field field = ProxyConnection.class.getDeclaredField("isCommitStateDirty");
        field.setAccessible(true);
        return field.getBoolean(connection);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jongo.model.IdSpecSet.java

public static <T> T id(T specInstance, Object id) {
    Field field = idField(specInstance.getClass());
    try {//from  w  w  w. j  av a2  s .  com
        field.setAccessible(true);
        if (ObjectId.class.isAssignableFrom(field.getType())) {
            field.set(specInstance, (ObjectId) id);
        } else {
            field.set(specInstance, id.toString());
        }
        return specInstance;
    } catch (Exception e) {
        throw new RuntimeException("could not set id field", e);
    }
}