java.lang.reflect.Field#isAccessible ( )源码实例Demo

下面列出了java.lang.reflect.Field#isAccessible ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: SonarPet   文件: ReflectionUtil.java
/**
 * Field stuff
 */

public static Field getField(Class<?> clazz, String fieldName) {
    try {
        Field field = clazz.getDeclaredField(fieldName);

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

        return field;
    } catch (NoSuchFieldException e) {
        EchoPet.LOG.warning("No such field: " + fieldName + "!");
        e.printStackTrace();
        return null;
    }
}
 
源代码2 项目: EchoPet   文件: ReflectionUtil.java
/**
 * Field stuff
 */

public static Field getField(Class<?> clazz, String fieldName) {
    try {
        Field field = clazz.getDeclaredField(fieldName);

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

        return field;
    } catch (NoSuchFieldException e) {
        EchoPet.LOG.warning("No such field: " + fieldName + "!");
        e.printStackTrace();
        return null;
    }
}
 
源代码3 项目: sarl   文件: TestReflections.java
/**
 * Set the value of the given accessible field of the given instance.
 * 
 * @param instance the container of the field, not {@code null}
 * @param fieldName the field's name, not {@code null}
 * @return the value of the field
 */
public static <T> void set(Object instance, String fieldName, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
	Class<?> type = instance.getClass();
	while (type != null) {
		try {
			Field f = getDeclaredField(type, fieldName);
			if (!f.isAccessible()) {
				f.setAccessible(true);
			}
			f.set(instance, value);
			return;
		} catch (NoSuchFieldException exception) {
			//
		}
		type = type.getSuperclass();
	}
	throw new NoSuchFieldException(fieldName);
}
 
源代码4 项目: LiveEventBus   文件: AppUtils.java
private static void fixSoftInputLeaks(final Activity activity) {
    if (activity == null) return;
    InputMethodManager imm =
            (InputMethodManager) AppUtils.getApp().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm == null) return;
    String[] leakViews = new String[]{"mLastSrvView", "mCurRootView", "mServedView", "mNextServedView"};
    for (String leakView : leakViews) {
        try {
            Field leakViewField = InputMethodManager.class.getDeclaredField(leakView);
            if (leakViewField == null) continue;
            if (!leakViewField.isAccessible()) {
                leakViewField.setAccessible(true);
            }
            Object obj = leakViewField.get(imm);
            if (!(obj instanceof View)) continue;
            View view = (View) obj;
            if (view.getRootView() == activity.getWindow().getDecorView().getRootView()) {
                leakViewField.set(imm, null);
            }
        } catch (Throwable ignore) { /**/ }
    }
}
 
源代码5 项目: BlogManagePlatform   文件: ReflectUtil.java
/**
 * 设置目标实体的指定字段的值
 * @param isExact value的类型是否匹配,如果匹配请选择true,速度更快
 * @author Frodez
 * @date 2019-12-29
 */
@SuppressWarnings("deprecation")
@SneakyThrows
public static void set(Class<?> klass, String fieldName, Object target, @Nullable Object value) {
	Assert.notNull(klass, "klass must not be null");
	Assert.notNull(fieldName, "fieldName must not be null");
	Assert.notNull(target, "target must not be null");
	Field field = klass.getDeclaredField(fieldName);
	if (!field.isAccessible()) {
		//暂时使用isAccessible api,因为可以减少判断次数提高性能
		field.trySetAccessible();
	}
	String identifier = StrUtil.concat(klass.getCanonicalName(), DefStr.POINT_SEPERATOR, fieldName);
	MethodHandle handle = SETTER_CACHE.get(identifier);
	if (handle == null) {
		handle = MethodHandles.lookup().unreflectSetter(field);
		SETTER_CACHE.put(identifier, handle);
	}
	handle.invoke(target, value);
}
 
源代码6 项目: ats-framework   文件: HiddenHtmlConfirm.java
public HiddenHtmlConfirm( UiDriver uiDriver ) {

        super(uiDriver);

        HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
        HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        Field webClientField = null;
        boolean fieldAccessibleState = false;
        try {

            TargetLocator targetLocator = driver.switchTo();
            webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
            fieldAccessibleState = webClientField.isAccessible();
            webClientField.setAccessible(true);
            webClient = (WebClient) webClientField.get(targetLocator.defaultContent());

        } catch (Exception e) {

            throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
        } finally {

            if (webClientField != null) {
                webClientField.setAccessible(fieldAccessibleState);
            }
        }
    }
 
源代码7 项目: tomee   文件: GlobalListenerSupport.java
/**
 * Setting monitoreable child field.
 *
 * @param containerBase host or engine
 */
@SuppressWarnings("unchecked")
private void addContextListener(final ContainerBase containerBase) {
    boolean accessible = false;
    Field field = null;
    try {
        field = ContainerBase.class.getDeclaredField("children");
        accessible = field.isAccessible();
        field.setAccessible(true);
        Map<Object, Object> children = (Map<Object, Object>) field.get(containerBase);
        if (children instanceof GlobalListenerSupport.MoniterableHashMap) {
            return;
        }
        children = new GlobalListenerSupport.MoniterableHashMap(children, containerBase, "children", this);
        field.set(containerBase, children);
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        if (field != null) {
            if (!accessible) {
                field.setAccessible(false);
            }
        }
    }

}
 
源代码8 项目: genie   文件: JobProcessManagerImpl.java
private long getPid(final Process process) {
    long pid = -1;
    final String processClassName = process.getClass().getCanonicalName();
    try {
        if ("java.lang.UNIXProcess".equals(processClassName)) {
            final Field pidMemberField = process.getClass().getDeclaredField("pid");
            final boolean resetAccessible = pidMemberField.isAccessible();
            pidMemberField.setAccessible(true);
            pid = pidMemberField.getLong(process);
            pidMemberField.setAccessible(resetAccessible);
        } else {
            log.debug("Don't know how to access PID for class {}", processClassName);
        }
    } catch (final Throwable t) {
        log.warn("Failed to determine job process PID");
    }
    return pid;
}
 
源代码9 项目: astor   文件: InjectingAnnotationEngine.java
private static Set<Object> scanMocks(Object testClass, Class<?> clazz) {
    Set<Object> mocks = new HashSet<Object>();
    for (Field field : clazz.getDeclaredFields()) {
        // mock or spies only
        if (null != field.getAnnotation(Spy.class) || null != field.getAnnotation(org.mockito.Mock.class)
                || null != field.getAnnotation(Mock.class)) {
            Object fieldInstance = null;
            boolean wasAccessible = field.isAccessible();
            field.setAccessible(true);
            try {
                fieldInstance = field.get(testClass);
            } catch (IllegalAccessException e) {
                throw new MockitoException("Problems injecting dependencies in " + field.getName(), e);
            } finally {
                field.setAccessible(wasAccessible);
            }
            if (fieldInstance != null) {
                mocks.add(fieldInstance);
            }
        }
    }
    return mocks;
}
 
源代码10 项目: astor   文件: FieldUtils.java
/**
 * Writes a field.
 * @param field to write
 * @param target  the object to call on, may be null for static fields
 * @param value to set
 * @param forceAccess  whether to break scope restrictions using the
 *  <code>setAccessible</code> method. <code>False</code> will only
 *  match public fields.
 * @throws IllegalArgumentException if the field is null
 * @throws IllegalAccessException if the field is not made accessible or is final
 */
public static void writeField(Field field, Object target, Object value, boolean forceAccess)
    throws IllegalAccessException {
    if (field == null) {
        throw new IllegalArgumentException("The field must not be null");
    }
    if (forceAccess && !field.isAccessible()) {
        field.setAccessible(true);
    } else {
        MemberUtils.setAccessibleWorkaround(field);
    }
    field.set(target, value);
}
 
源代码11 项目: sofa-ark   文件: ReflectionUtils.java
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);
    }
}
 
源代码12 项目: netty-4.1.22   文件: Log4J2LoggerTest.java
@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Class<?> clazz, String fieldName) {
    try {
        Field field = clazz.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            Assume.assumeThat(ReflectionUtil.trySetAccessible(field, true), CoreMatchers.nullValue());
        }
        return (T) field.get(AbstractInternalLogger.class);
    } catch (ReflectiveOperationException e) {
        throw new IllegalStateException(e);
    }
}
 
源代码13 项目: tomee   文件: ServerListener.java
private synchronized void installServerInfo() {
    if (SystemInstance.get().getOptions().get("tomee.keep-server-info", false)) {
        return;
    }

    // force static init
    final String value = ServerInfo.getServerInfo();

    Field field = null;
    boolean acc = true;
    try {
        field = ServerInfo.class.getDeclaredField("serverInfo");
        acc = field.isAccessible();
        final int slash = value.indexOf('/');
        field.setAccessible(true);
        final String tomeeVersion = OpenEjbVersion.get().getVersion();
        final int modifiers = field.getModifiers();
        if (Modifier.isFinal(modifiers)) { // this is a bit fragile, we can surely drop this feature at some point
            final Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, modifiers & ~Modifier.FINAL);
        }
        field.set(null, value.substring(0, slash) + " (TomEE)" + value.substring(slash) + " (" + tomeeVersion + ")");
    } catch (final Exception e) {
        // no-op
    } finally {
        if (field != null) {
            field.setAccessible(acc);
        }
    }
}
 
源代码14 项目: astor   文件: FieldUtils.java
/**
 * Write a field.
 * @param field to write
 * @param target  the object to call on, may be null for static fields
 * @param value to set
 * @param forceAccess  whether to break scope restrictions using the
 *  <code>setAccessible</code> method. <code>False</code> will only
 *  match public fields.
 * @throws IllegalArgumentException if the field is null
 * @throws IllegalAccessException if the field is not made accessible or is final
 */
public static void writeField(Field field, Object target, Object value, boolean forceAccess) throws IllegalAccessException {
    if (field == null) {
        throw new IllegalArgumentException("The field must not be null");
    }
    if (forceAccess && !field.isAccessible()) {
        field.setAccessible(true);
    } else {
        MemberUtils.setAccessibleWorkaround(field);
    }
    field.set(target, value);
}
 
源代码15 项目: Robust   文件: EnhancedRobustUtils.java
private static Field getReflectStaticField(String name, Class clazz) throws NoSuchFieldException {
    try {
        Field field = clazz.getDeclaredField(name);
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        return field;
    } catch (NoSuchFieldException e) {
        // ignore and search next
        e.printStackTrace();
    }
    throw new NoSuchFieldException("Field " + name + " not found in " + clazz);
}
 
源代码16 项目: xtext-lib   文件: ReflectExtensions.java
/**
 * Retrieves the value of the given accessible field of the given receiver.
 * 
 * @param receiver the container of the field, not <code>null</code>
 * @param fieldName the field's name, not <code>null</code>
 * @return the value of the field
 * 
 * @throws NoSuchFieldException see {@link Class#getField(String)}
 * @throws SecurityException see {@link Class#getField(String)}
 * @throws IllegalAccessException see {@link Field#get(Object)}
 * @throws IllegalArgumentException see {@link Field#get(Object)}
 */
@SuppressWarnings("unchecked")
/* @Nullable */
public <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
	Preconditions.checkNotNull(receiver,"receiver");
	Preconditions.checkNotNull(fieldName,"fieldName");
	
	Class<? extends Object> clazz = receiver.getClass();
	Field f = getDeclaredField(clazz, fieldName);
	if (!f.isAccessible())
		f.setAccessible(true);
	return (T) f.get(receiver);
}
 
源代码17 项目: jpmml-sklearn   文件: SkLearnEncoder.java
public void renameFeature(Feature feature, FieldName renamedName){
	FieldName name = feature.getName();

	org.dmg.pmml.Field<?> pmmlField = getField(name);

	if(pmmlField instanceof DataField){
		throw new IllegalArgumentException("User input field " + name.getValue() + " cannot be renamed");
	}

	DerivedField derivedField = removeDerivedField(name);

	try {
		Field field = Feature.class.getDeclaredField("name");

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

		field.set(feature, renamedName);
	} catch(ReflectiveOperationException roe){
		throw new RuntimeException(roe);
	}

	derivedField.setName(renamedName);

	addDerivedField(derivedField);
}
 
源代码18 项目: Bailan   文件: BaseActivity.java
/**
 * 解决InputMethodManager内存泄露现象
 */
private 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;
    Object obj_get;
    for (String param : arr) {
        try {
            f = imm.getClass().getDeclaredField(param);
            if (!f.isAccessible()) {
                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循环了
                    /*if (QLog.isColorLevel()) {
                        QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
                    }*/
                    break;
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
 
源代码19 项目: j360-dubbo-app-all   文件: ClassUtil.java
/**
 * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
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);
	}
}
 
源代码20 项目: dolphin   文件: ReflectionUtils.java
/**
 * 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);
	}
}