Java Code Examples for java.lang.reflect.Field#trySetAccessible()

The following examples show how to use java.lang.reflect.Field#trySetAccessible() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectUtil.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 设置目标实体的指定字段的值
 * @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);
}
 
Example 2
Source File: ReflectUtil.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 设置目标实体的指定字段的值
 * @param isExact value的类型是否匹配,如果匹配请选择true,速度更快
 * @author Frodez
 * @date 2019-12-29
 */
@SuppressWarnings("deprecation")
@SneakyThrows
public static void set(Field field, Object target, @Nullable Object value) {
	Assert.notNull(field, "field must not be null");
	Assert.notNull(target, "target must not be null");
	if (!field.isAccessible()) {
		//暂时使用isAccessible api,因为可以减少判断次数提高性能
		field.trySetAccessible();
	}
	String identifier = StrUtil.concat(field.getDeclaringClass().getCanonicalName(), DefStr.POINT_SEPERATOR, field.getName());
	MethodHandle handle = SETTER_CACHE.get(identifier);
	if (handle == null) {
		handle = MethodHandles.lookup().unreflectGetter(field);
		GETTER_CACHE.put(identifier, handle);
	}
	handle.invoke(target, value);
}
 
Example 3
Source File: ReflectUtil.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 获取目标实体的指定字段
 * @author Frodez
 * @date 2019-12-29
 */
@SuppressWarnings("deprecation")
@SneakyThrows
public static Object get(Class<?> klass, String fieldName, Object target) {
	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 = GETTER_CACHE.get(identifier);
	if (handle == null) {
		handle = MethodHandles.lookup().unreflectGetter(field);
		GETTER_CACHE.put(identifier, handle);
	}
	return handle.invoke(target);
}
 
Example 4
Source File: ReflectUtil.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 获取目标实体的指定字段
 * @author Frodez
 * @date 2019-12-29
 */
@SuppressWarnings("deprecation")
@SneakyThrows
public static Object get(Field field, Object target) {
	Assert.notNull(field, "field must not be null");
	Assert.notNull(target, "target must not be null");
	if (!field.isAccessible()) {
		//暂时使用isAccessible api,因为可以减少判断次数提高性能
		field.trySetAccessible();
	}
	String identifier = StrUtil.concat(field.getDeclaringClass().getCanonicalName(), DefStr.POINT_SEPERATOR, field.getName());
	MethodHandle handle = GETTER_CACHE.get(identifier);
	if (handle == null) {
		handle = MethodHandles.lookup().unreflectGetter(field);
		GETTER_CACHE.put(identifier, handle);
	}
	return handle.invoke(target);
}
 
Example 5
Source File: BeanFactory.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
public <T> void inject(T instance) {
    try {
        Class<?> visitorType = instance.getClass();
        while (!visitorType.equals(Object.class)) {
            for (Field field : visitorType.getDeclaredFields()) {
                if (field.isAnnotationPresent(Inject.class)) {
                    if (Modifier.isStatic(field.getModifiers()))
                        throw new Error("static field must not have @Inject, field=" + Fields.path(field));
                    if (field.trySetAccessible()) {
                        field.set(instance, lookupValue(field));
                    } else {
                        throw new Error("failed to inject field, field=" + Fields.path(field));
                    }
                }
            }
            visitorType = visitorType.getSuperclass();
        }
    } catch (IllegalAccessException e) {
        throw new Error(e);
    }
}
 
Example 6
Source File: EntityHandler.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Object handleType(ResultSet resultSet, Class<?> type) throws SQLException {
    try {
        var instance = type.getDeclaredConstructor().newInstance();
        var fields = Util.fieldsOf(type);

        var metaData = resultSet.getMetaData();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            var columnName = metaData.getColumnLabel(i);

            Field f = findField(fields, columnName);
            if(isNull(f)) {
                LOGGER.debug("There is no field with name {} on Type {}",  columnName, type.getName());
                continue;
            }
            if(f.trySetAccessible()) {
                var handler = TypeHandler.MAP.getOrDefault(f.getType().isEnum() ? "enum" : f.getType().getName(), TypeHandler.MAP.get(Object.class.getName()));
                f.set(instance, handler.handleColumn(resultSet, i, f.getType()));
            } else {
                throw new SQLException("No accessible field " + f.getName() + " On type " + type );
            }
        }
        return instance;
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new SQLException(e);
    }
}
 
Example 7
Source File: BeanUtil.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
private static boolean isPrivateAndNotNullField(Field field, Object bean) throws IllegalArgumentException, IllegalAccessException {
	return Modifier.PRIVATE == field.getModifiers() && field.trySetAccessible() && field.get(bean) != null;
}