Java Code Examples for java.lang.reflect.Field.isAccessible()

The following are Jave code examples for showing how to use isAccessible() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: ShareReflectUtil.java   View Source Code Vote up 6 votes
public static Field findField(Class<?> originClazz, String name) throws NoSuchFieldException {
    for (Class<?> clazz = originClazz; clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Field field = clazz.getDeclaredField(name);

            if (!field.isAccessible()) {
                field.setAccessible(true);
            }

            return field;
        } catch (NoSuchFieldException e) {
            // ignore and search next
        }
    }

    throw new NoSuchFieldException("Field " + name + " not found in " + originClazz);
}
 
Example 2
Project: atlas   File: NClassLoader.java   View Source Code Vote up 6 votes
public static Field findField(Object instance, String name) throws NoSuchFieldException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Field field = clazz.getDeclaredField(name);

            if (!field.isAccessible()) {
                field.setAccessible(true);
            }

            return field;
        } catch (NoSuchFieldException e) {
            // ignore and search next
        }
    }

    throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
}
 
Example 3
Project: oma-riista-android   File: RemoteObject.java   View Source Code Vote up 6 votes
/**
 * This method is for internal user only.
 */
public void updateFields(T object)
{
    long version = getObjectVersion();
    RemoteObject<?> other = (RemoteObject<?>)object;
    if (version < 0 || other.getObjectVersion() > version) {
        //We have invalid version value or the other one is newer.
        
        for (Field f : mFields) {
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            try {
                Object fieldValue = f.get(object);
                f.set(this, fieldValue);
            } 
            catch (Exception e) {
                throw new RuntimeException(e);
            } 
        }
        saveSnapshotState();
    }
}
 
Example 4
Project: ipayquery   File: ReflectHelper.java   View Source Code Vote up 6 votes
/**
 * 获取obj对象fieldName的属性值
 * 
 * @param obj
 * @param fieldName
 * @return
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static Object getValueByFieldName(Object obj, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException {
    Field field = getFieldByFieldName(obj, fieldName);
    Object value = null;
    if (field != null) {
        if (field.isAccessible()) {
            value = field.get(obj);
        } else {
            field.setAccessible(true);
            value = field.get(obj);
            field.setAccessible(false);
        }
    }
    return value;
}
 
Example 5
Project: ExPetrum   File: ExPetrum.java   View Source Code Vote up 6 votes
private void setDevEnvironment()
{
	try
	{
		Class<CoreModManager> clazz = CoreModManager.class;
		Field f = clazz.getDeclaredField("deobfuscatedEnvironment");
		boolean accessibilityFlag = f.isAccessible();
		f.setAccessible(true);
		isDevEnvironment = f.getBoolean(null);
		f.setAccessible(accessibilityFlag);
		if (isDevEnvironment)
		{
			ExPMisc.modLogger.log(LogLevel.Fine, "ExPetrum has detected dev environment! Additional debug features enabled!");
			ExPMisc.modLogger.setLevel(LogLevel.Debug);
		}
		else
		{
			ExPMisc.modLogger.log(LogLevel.Fine, "ExPetrum has detected normal minecraft environment. No debug features enabled.");
		}
	}
	catch (Exception ex)
	{
		ExPMisc.modLogger.log(LogLevel.Warning, "ExPetrum was unable to determine the environment it is located in! Assuming normal minecraft instance.");
	}
}
 
Example 6
Project: ChocoPie   File: Reflector.java   View Source Code Vote up 6 votes
public static Object readValue(Object instance, Field field) throws ReflectorException {
    if (instance == null) {
        return null;
    }

    boolean originalAccessibility = field.isAccessible();
    field.setAccessible(true);

    try {
        return field.get(instance);
    } catch (IllegalAccessException e) {
        throw new ReflectorException("Unable to manipulate field accessibility.", e);
    } finally {
        field.setAccessible(originalAccessibility);
    }
}
 
Example 7
Project: lazycat   File: DefaultInstanceManager.java   View Source Code Vote up 6 votes
/**
 * Inject resources in specified field.
 *
 * @param context
 *            jndi context to extract value from
 * @param instance
 *            object to inject into
 * @param field
 *            field target for injection
 * @param name
 *            jndi name value is bound under
 * @param clazz
 *            class annotation is defined in
 * @throws IllegalAccessException
 *             if field is inaccessible
 * @throws javax.naming.NamingException
 *             if value is not accessible in naming context
 */
protected static void lookupFieldResource(Context context, Object instance, Field field, String name,
		Class<?> clazz) throws NamingException, IllegalAccessException {

	Object lookedupResource;
	boolean accessibility;

	String normalizedName = normalize(name);

	if ((normalizedName != null) && (normalizedName.length() > 0)) {
		lookedupResource = context.lookup(normalizedName);
	} else {
		lookedupResource = context.lookup(clazz.getName() + "/" + field.getName());
	}

	synchronized (field) {
		accessibility = field.isAccessible();
		field.setAccessible(true);
		field.set(instance, lookedupResource);
		field.setAccessible(accessibility);
	}
}
 
Example 8
Project: ProjectAres   File: Fields.java   View Source Code Vote up 5 votes
public static void writeField(@Nullable Object obj, Field field, Object value) {
    final boolean wasAccessible = field.isAccessible();
    try {
        field.setAccessible(true);
        field.set(obj, value);
    } catch(IllegalAccessException e) {
        throw new RuntimeException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}
 
Example 9
Project: tasfe-framework   File: EnumFieldReflectUtil.java   View Source Code Vote up 5 votes
/**
 * 获取枚举类型的字段值-ordinal
 *
 * @param target the target object from which to get the field
 * @param field  the field to get
 * @return enum.ordinal
 * @throws Exception IllegalArgumentException, IllegalAccess
 */
@SuppressWarnings("rawtypes")
public static int getFieldEnumOrdinal(Object target, Field field) throws Exception {
    if (field.getType().isEnum()) {
        if (!field.isAccessible()) {
            ReflectionUtils.makeAccessible(field);
        }
        return ((Enum) field.get(target)).ordinal();
    } else {
        throw new ReflectionException(target.getClass().getName() + "." + field.getName()
                + ":field type is not Enum, can not convertToEnum");
    }
}
 
Example 10
Project: shareNote   File: LeakUtil.java   View Source Code Vote up 5 votes
/**
 * InputMethodManager导致的内存泄露
 * from: http://blog.csdn.net/sodino/article/details/32188809
 * @param destContext
 */
public static void fixInputMethodManagerLeak(Context destContext) {
    if (destContext == null) {
        return;
    }

    InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm == null) {
        return;
    }

    String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
    Field f = null;
    Object obj_get = null;
    for (int i = 0;i < arr.length;i ++) {
        String param = arr[i];
        try{
            f = imm.getClass().getDeclaredField(param);
            if (f.isAccessible() == false) {
                f.setAccessible(true);
            } // author: sodino mail:[email protected]
            obj_get = f.get(imm);
            if (obj_get != null && obj_get instanceof View) {
                View v_get = (View) obj_get;
                if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                    f.set(imm, null); // 置空,破坏掉path to gc节点
                } else {
                    // 不是想要目标销毁的,即为又进了另一层界面了,不要处理,避免影响原逻辑,也就不用继续for循环了
                    break;
                }
            }
        }catch(Throwable t){
            t.printStackTrace();
        }
    }
}
 
Example 11
Project: neoscada   File: AnnotationMessageProcessor.java   View Source Code Vote up 5 votes
protected void processFields ( final FieldProcessor processor )
{
    for ( final Field field : Reflections.findAllFields ( this.target.getClass () ) )
    {
        final Message message = field.getAnnotation ( Message.class );
        if ( message == null )
        {
            continue;
        }

        if ( !field.isAccessible () )
        {
            field.setAccessible ( true );
            try
            {
                processor.process ( this.target, field, message );
            }
            finally
            {
                field.setAccessible ( false );
            }
        }
        else
        {
            processor.process ( this.target, field, message );
        }
    }
}
 
Example 12
Project: OnlineShop   File: CSVProcessor.java   View Source Code Vote up 5 votes
private void setFieldValue(Field field, T object, Object value) throws IllegalArgumentException, IllegalAccessException {
    if (field.isAccessible()) {
        field.set(object, value);
    } else {
        field.setAccessible(true);
        field.set(object, value);
        field.setAccessible(false);
    }
}
 
Example 13
Project: angit   File: Reflections.java   View Source Code Vote up 5 votes
/**
 * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 *
 * @param field the field
 */
public static void makeAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
        .isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}
 
Example 14
Project: ClientAPI   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Gets the value of a field from an Object
 *
 * @param object Object that field belongs to
 * @param field Field that is being retrieved
 * @return The value of the field
 */
public static Object getField(Object object, Field field) {
    Object value = null;
    try {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        value = field.get(object);
        field.setAccessible(accessible);
    } catch (NullPointerException | IllegalAccessException ignored) {}
    return value;
}
 
Example 15
Project: EchoPet   File: SafeField.java   View Source Code Vote up 5 votes
protected void setField(Field field) {
    if (!field.isAccessible()) {
        try {
            field.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
            field = null;
        }
    }
    this.field = field;
    this.isStatic = Modifier.isStatic(field.getModifiers());
}
 
Example 16
Project: CBLMapper   File: CBLDocument.java   View Source Code Vote up 5 votes
public void setDocumentID(String documentID) {
    mDocumentID = documentID;
    mDocument = null;
    // Inject Document ID into CBLDocument attributes with annotation @DocumentField(ID=true)
    for (Field field : FieldHelper.getFieldsUpTo(this.getClass(), Object.class)) {
        DocumentField documentFieldAnnotation = field.getAnnotation(DocumentField.class);
        if (documentFieldAnnotation != null && documentFieldAnnotation.ID()) {
            if (field.getType() == String.class) {
                try {
                    boolean isPrivate = !field.isAccessible();
                    if (isPrivate) {
                        field.setAccessible(true);
                    }
                    field.set(this, documentID);
                    if (isPrivate) {
                        field.setAccessible(false);
                    }
                } catch (IllegalAccessException e) {
                    // Ignore as it can't happen
                }
                break;
            } else {
                throw new UnsupportedIDFieldTypeException(this.getClass());
            }
        }
    }
}
 
Example 17
Project: boohee_v5.6   File: ShareReflectUtil.java   View Source Code Vote up 5 votes
public static Field findField(Object instance, String name) throws NoSuchFieldException {
    Class<?> clazz = instance.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(name);
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            return field;
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        }
    }
    throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
}
 
Example 18
Project: java-validator-safeguard   File: ParamVerify.java   View Source Code Vote up 5 votes
/**
 * Método private que valida um objeto que tem atributos anotados com <code>@Verify</code>
 * <p>Verifica se o atributo da classe é acessível e está anotado</p>
 * 
 * @param field Atributos da classe anotadas com (@Verify)
 * @return boolean <code>true</code> se for acessível e estiver anotado
 * 		 		   <code>false</code> caso contrário
 */
private boolean isVerifiable(Field field) {
	
	field.setAccessible(true);
	if (field.isAccessible() && field.isAnnotationPresent(Verify.class)) {
		return true;
	}
	return false;
}
 
Example 19
Project: neoscada   File: InjectHelper.java   View Source Code Vote up 5 votes
/**
 * Set a field value
 * <p>
 * The method will try to set the field using a setter first.
 * </p>
 * 
 * @param target
 *            the target object
 * @param field
 *            the field to set
 * @param value
 *            the value to set
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static void setField ( final Object target, final Field field, final Object value ) throws IllegalArgumentException, IllegalAccessException
{
    try
    {
        // try setter first
        final Method setter = target.getClass ().getMethod ( "set" + StringHelper.toUpperFirst ( field.getName () ), field.getType () );
        setter.invoke ( target, value );
    }
    catch ( final Exception e )
    {
        // continue with field access
    }

    if ( field.isAccessible () )
    {
        field.set ( target, value );
    }
    else
    {
        field.setAccessible ( true );
        try
        {
            field.set ( target, value );
        }
        finally
        {
            field.setAccessible ( false );
        }
    }
}
 
Example 20
Project: spark-project   File: ReflectionUtils.java   View Source Code Vote up 3 votes
/**
 * Make the given field accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param field the field to make accessible
 * @see java.lang.reflect.Field#setAccessible
 */
public static void makeAccessible(Field field) {
	if ((!Modifier.isPublic(field.getModifiers()) ||
			!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
			Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
		field.setAccessible(true);
	}
}