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:com.nridge.core.base.field.data.DataBeanBag.java

/**
 * Accepts a POJO containing one or more public fields and
 * creates a DataBag from them.  The DataBeanObject1 test
 * class provides a reference example.//  w ww  . j  av a  2 s.  co m
 *
 * @param anObject POJO instance.
 *
 * @return Data bag instance populated with field information.
 *
 * @throws NSException Thrown if object is null.
 * @throws NoSuchFieldException Thrown if field does not exist.
 * @throws IllegalAccessException Thrown if access is illegal.
 */
public static DataBag fromFieldsToBag(Object anObject)
        throws NSException, NoSuchFieldException, IllegalAccessException {
    DataField dataField;
    boolean isPublicAccess;

    if (anObject == null)
        throw new NSException("Object is null");

    DataBag dataBag = new DataBag(anObject.toString());

    Class<?> objClass = anObject.getClass();
    Field[] fieldArray = objClass.getDeclaredFields();
    for (Field objField : fieldArray) {
        isPublicAccess = Modifier.isPublic(objField.getModifiers());
        if (!isPublicAccess)
            objField.setAccessible(true);
        dataField = reflectField(anObject, objField);
        dataBag.add(dataField);

    }

    return dataBag;
}

From source file:ml.shifu.shifu.util.ClassUtils.java

private static void setFieldValue(Field field, Object instance, Object value)
        throws IllegalArgumentException, IllegalAccessException {
    field.setAccessible(true);
    field.set(instance, value);/* w  ww . ja va2  s .  c om*/
}

From source file:android.framework.util.jar.Manifest.java

private static Field getByteArrayInputStreamField(String name) {
    try {//ww w. j  a  va2s  .com
        Field f = ByteArrayInputStream.class.getDeclaredField(name);
        f.setAccessible(true);
        return f;
    } catch (Exception ex) {
        throw new AssertionError(ex);
    }
}

From source file:me.neatmonster.spacebukkit.PanelListener.java

public static String dump(Object object) {
    Field[] fields = object.getClass().getDeclaredFields();
    StringBuilder sb = new StringBuilder();
    sb.append(object.getClass().getSimpleName()).append('{');

    boolean firstRound = true;

    for (Field field : fields) {
        if (!firstRound) {
            sb.append(", ");
        }/*ww w .ja  v a2 s.  com*/
        firstRound = false;
        field.setAccessible(true);
        try {
            final Object fieldObj = field.get(object);
            final String value;
            if (null == fieldObj) {
                value = "null";
            } else {
                value = fieldObj.toString();
            }
            sb.append(field.getName()).append('=').append('\'').append(value).append('\'');
        } catch (IllegalAccessException ignore) {
            //this should never happen
        }

    }

    sb.append('}');
    return sb.toString();
}

From source file:com.junly.common.util.ReflectUtils.java

/**
 * <p class="detail">//from w w w  .jav  a2 s.  c o  m
 * ?
 * </p>
 * @author wan.Dong
 * @date 20161112 
 * @param obj   
 * @param name   ??
 * @return
 */
public static Object getProperty(Object obj, String name) {
    if (obj != null) {
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            Field field = null;
            try {
                field = clazz.getDeclaredField(name);
            } catch (Exception e) {
                clazz = clazz.getSuperclass();
                continue;
            }
            try {
                field.setAccessible(true);
                return field.get(obj);
            } catch (Exception e) {
                return null;
            } finally {
                field.setAccessible(false);
            }
        }
    }
    return null;
}

From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java

public static <T> T parse(Class<T> target, String text) throws Exception {
    T bean = target.newInstance();/*from w  ww  .  j  a  v a2s.  co  m*/
    final List<Field> props = new LinkedList<>();
    ReflectionUtils.doWithFields(target, new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            props.add(field);
        }
    });
    JXDocument jxDocument = new JXDocument(text);
    for (Field f : props) {
        Xpath xpathInfo = f.getAnnotation(Xpath.class);
        if (xpathInfo != null) {
            String xpath = xpathInfo.value();
            List<Object> res = jxDocument.sel(xpath);
            boolean accessFlag = f.isAccessible();
            f.setAccessible(true);
            f.set(bean, defaultCastToTargetValue(target, f, res));
            f.setAccessible(accessFlag);
        }
    }
    return bean;
}

From source file:net.dv8tion.jda.utils.DebugUtil.java

public static JSONObject fromJDA(JDA iJDA, boolean includeUsers, boolean includeGuilds,
        boolean includeGuildUsers, boolean includeChannels, boolean includePrivateChannels) {
    JDAImpl jda = (JDAImpl) iJDA;/*w  w w . j  a  va  2 s  .c  om*/
    JSONObject obj = new JSONObject();
    obj.put("self_info", fromUser(jda.getSelfInfo()))
            .put("proxy",
                    jda.getGlobalProxy() == null ? JSONObject.NULL
                            : new JSONObject().put("host", jda.getGlobalProxy().getHostName()).put("port",
                                    jda.getGlobalProxy().getPort()))
            .put("response_total", jda.getResponseTotal()).put("audio_enabled", jda.isAudioEnabled())
            .put("auto_reconnect", jda.isAutoReconnect());

    JSONArray array = new JSONArray();
    for (Object listener : jda.getRegisteredListeners())
        array.put(listener.getClass().getCanonicalName());
    obj.put("event_listeners", array);

    try {
        Field f = EntityBuilder.class.getDeclaredField("cachedJdaGuildJsons");
        f.setAccessible(true);
        HashMap<String, JSONObject> cachedJsons = ((HashMap<JDA, HashMap<String, JSONObject>>) f.get(null))
                .get(jda);

        array = new JSONArray();
        for (String guildId : cachedJsons.keySet())
            array.put(guildId);
        obj.put("second_pass_json_guild_ids", array);

        f = EntityBuilder.class.getDeclaredField("cachedJdaGuildCallbacks");
        f.setAccessible(true);
        HashMap<String, Consumer<Guild>> cachedCallbacks = ((HashMap<JDA, HashMap<String, Consumer<Guild>>>) f
                .get(null)).get(jda);

        array = new JSONArray();
        for (String guildId : cachedCallbacks.keySet())
            array.put(guildId);
        obj.put("second_pass_callback_guild_ids", array);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    if (includeGuilds) {
        array = new JSONArray();
        for (Guild guild : jda.getGuilds())
            array.put(fromGuild(guild, includeGuildUsers, includeChannels, true, true));
        obj.put("guilds", array);
    }

    if (includePrivateChannels) {
        array = new JSONArray();
        for (PrivateChannel chan : jda.getPrivateChannels())
            array.put(fromPrivateChannel(chan, false));
        obj.put("private_channels", array);

        array = new JSONArray();
        for (Map.Entry<String, String> entry : jda.getOffline_pms().entrySet()) {
            array.put(new JSONObject().put("id", entry.getValue()).put("user_id", entry.getKey()));
        }
        obj.put("offline_private_channels", array);
    }

    if (includeUsers) {
        array = new JSONArray();
        for (User user : jda.getUsers())
            array.put(fromUser(user));
        obj.put("users", array);
    }

    return obj;
}

From source file:com.linkedin.pinot.common.utils.MmapUtils.java

private static void clearSynchronizedMapEntrySetCache() {
    // For some bizarre reason, Collections.synchronizedMap's implementation (at least on JDK 1.8.0.25) caches the
    // entry set, and will thus return stale (and incorrect) values if queried multiple times, as well as cause those
    // entries to not be garbage-collectable. This clears its cache.
    try {//w w  w .  j a  va 2s. c o  m
        Class<?> clazz = BUFFER_TO_CONTEXT_MAP.getClass();
        Field field = clazz.getDeclaredField("entrySet");
        field.setAccessible(true);
        field.set(BUFFER_TO_CONTEXT_MAP, null);
    } catch (Exception e) {
        // Well, that didn't work.
    }
}

From source file:com.gson.WeChat.java

/**
 * ???/* w ww . j a  v  a 2s .c om*/
 * @param oms
 * @param msg
 * @throws Exception
 */
private static void setMsgInfo(OutMessage oms, InMessage msg) throws Exception {
    if (oms != null) {
        Class<?> outMsg = oms.getClass().getSuperclass();
        Field CreateTime = outMsg.getDeclaredField("CreateTime");
        Field ToUserName = outMsg.getDeclaredField("ToUserName");
        Field FromUserName = outMsg.getDeclaredField("FromUserName");

        ToUserName.setAccessible(true);
        CreateTime.setAccessible(true);
        FromUserName.setAccessible(true);

        CreateTime.set(oms, new Date().getTime());
        ToUserName.set(oms, msg.getFromUserName());
        FromUserName.set(oms, msg.getToUserName());
    }
}

From source file:com.netflix.spinnaker.clouddriver.aws.security.AmazonClientInvocationHandler.java

private static Collection<String> getRequestIds(AmazonWebServiceRequest request, String idFieldName) {
    if (request == null) {
        return Collections.emptySet();
    }/*ww w .  ja  v  a  2  s . c  o m*/
    try {
        Field field = request.getClass().getDeclaredField(idFieldName);
        field.setAccessible(true);
        Collection<String> collection = (Collection<String>) field.get(request);
        return collection == null ? Collections.emptySet() : collection;
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}