Java源码示例:com.jstarcraft.core.common.reflection.ReflectionUtility
示例1
@Override
public boolean postProcessAfterInstantiation(final Object object, String name) throws BeansException {
ReflectionUtility.doWithFields(object.getClass(), (field) -> {
ResourceAccessor annotation = field.getAnnotation(ResourceAccessor.class);
if (annotation == null) {
return;
}
if (ResourceManager.class.isAssignableFrom(field.getType())) {
// 装配仓储
assembleStorage(object, field, annotation);
} else {
// 装配实例
assembleInstance(object, field, annotation);
}
});
return super.postProcessAfterInstantiation(object, name);
}
示例2
@Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor session, Object object) throws HibernateException, SQLException {
if (object == null) {
return null;
}
String json = resultSet.getString(names[0]);
String columnName = getColumnName(resultSet, names[0]);
String fieldName = getFieldName(object.getClass(), columnName);
Type type = null;
try {
type = ReflectionUtility.findField(object.getClass(), fieldName).getGenericType();
} catch (Exception exception) {
throw new StorageAccessException(exception);
}
Object value = JsonUtility.string2Object(json, type);
return value;
}
示例3
@Override
public boolean postProcessAfterInstantiation(final Object instance, final String name) throws BeansException {
ReflectionUtility.doWithFields(instance.getClass(), (field) -> {
CacheAccessor annotation = field.getAnnotation(CacheAccessor.class);
if (annotation == null) {
return;
}
if (field.getType().equals(EntityManager.class)) {
// 注入实体单位缓存服务
assembleEntityManager(instance, name, field);
} else if (field.getType().equals(RegionManager.class)) {
// 注入区域单位缓存服务
assembleRegionManager(instance, name, field);
} else {
String message = StringUtility.format("无法装配Bean[{}]的属性[{}]", name, field.getName());
LOGGER.error(message);
throw new CacheConfigurationException(message);
}
});
return super.postProcessAfterInstantiation(instance, name);
}
示例4
private ClassDefinition(int code, Class<?> clazz, TreeSet<PropertyDefinition> properties, Specification specification) {
this.code = code;
this.clazz = clazz;
this.name = clazz.getName();
this.specification = specification;
this.properties = properties.toArray(new PropertyDefinition[properties.size()]);
// 不是所有类型都有无参数构造器
for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
if (constructor.getParameterTypes().length == 0) {
ReflectionUtility.makeAccessible(constructor);
this.constructor = constructor;
break;
}
}
// if (this.constructor == null && !this.clazz.isEnum()) {
// String message = StringUtility.format("类型[{}]缺乏无参数构造器,不符合编解码规范",
// clazz.getName());
// throw new CodecException(message);
// }
}
示例5
private Object execute(Class<? extends LockableStrategy> clazz, ProceedingJoinPoint point, Signature signature) throws Throwable {
Method method = ((MethodSignature) signature).getMethod();
// 获取锁策略
LockableStrategy strategy = strategies.get(method);
if (strategy == null) {
synchronized (method) {
if (strategy == null) {
strategy = ReflectionUtility.getInstance(clazz, method);
strategies.put(method, strategy);
}
}
}
Object[] arguments = point.getArgs();
try (Lockable lock = strategy.getLock(arguments)) {
lock.open();
return point.proceed(arguments);
}
}
示例6
private Model getModel(Class<? extends Model> clazz, DataSpace dataSpace, DataModule dataModule) throws Exception {
Model model = ReflectionUtility.getInstance(clazz);
EnvironmentContext context = EnvironmentFactory.getContext();
Future<?> task = context.doTask(() -> {
model.prepare(configuration, dataModule, dataSpace);
model.practice();
});
task.get();
return model;
}
示例7
/**
* initialization
*
* @throws ModelException if error occurs
*/
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
super.prepare(configuration, model, space);
similarityFilter = configuration.getFloat("recommender.sim.filter", 4F);
float denominator = 0F;
itemWeights = DenseVector.valueOf(itemSize);
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
float numerator = scoreMatrix.getColumnScope(itemIndex);
denominator = denominator < numerator ? numerator : denominator;
itemWeights.setValue(itemIndex, numerator);
}
// compute item relative importance
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
itemWeights.setValue(itemIndex, itemWeights.getValue(itemIndex) / denominator);
}
// compute item correlations by cosine similarity
// TODO 修改为配置枚举
try {
Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
itemCorrelations = new SymmetryMatrix(scoreMatrix.getColumnSize());
correlation.calculateCoefficients(scoreMatrix, true, itemCorrelations::setValue);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
示例8
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
super.prepare(configuration, model, space);
userFactors = DenseMatrix.valueOf(userSize, factorSize);
userFactors.iterateElement(MathCalculator.SERIAL, (scalar) -> {
scalar.setValue(RandomUtility.randomFloat(1F));
});
itemFactors = DenseMatrix.valueOf(itemSize, factorSize);
itemFactors.iterateElement(MathCalculator.SERIAL, (scalar) -> {
scalar.setValue(RandomUtility.randomFloat(1F));
});
// TODO 修改为配置枚举
try {
Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
socialCorrelations = new SymmetryMatrix(socialMatrix.getRowSize());
correlation.calculateCoefficients(socialMatrix, false, socialCorrelations::setValue);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
for (MatrixScalar term : socialCorrelations) {
float similarity = term.getValue();
if (similarity == 0F) {
continue;
}
similarity = (1F + similarity) / 2F;
term.setValue(similarity);
}
}
示例9
protected AbstractTask(Class<? extends Model> clazz, Configurator configurator) {
this.configurator = configurator;
Long seed = configurator.getLong("recommender.random.seed");
if (seed != null) {
RandomUtility.setSeed(seed);
}
this.model = (Model) ReflectionUtility.getInstance(clazz);
}
示例10
public QualityProbability(Class<? extends RandomGenerator> randomClazz, int randomSeed, Class<? extends AbstractIntegerDistribution> distributionClazz, Object... distributionParameters) {
this.randomSeed = randomSeed;
this.random = ReflectionUtility.getInstance(randomClazz, randomSeed);
this.distributionParameters = distributionParameters;
distributionParameters = ArrayUtility.insert(0, distributionParameters, random);
this.distribution = ReflectionUtility.getInstance(distributionClazz, distributionParameters);
}
示例11
@Override
public void afterLoad() {
try {
random = (RandomGenerator) ReflectionUtility.getInstance(Class.forName(randomClass), randomSeed);
Object[] parameters = ArrayUtility.insert(0, distributionParameters, random);
distribution = (AbstractIntegerDistribution) ReflectionUtility.getInstance(Class.forName(distributionClass), parameters);
} catch (Exception exception) {
}
}
示例12
public QuantityProbability(Class<? extends RandomGenerator> randomClazz, int randomSeed, Class<? extends AbstractRealDistribution> distributionClazz, Object... distributionParameters) {
this.randomSeed = randomSeed;
this.random = ReflectionUtility.getInstance(randomClazz, randomSeed);
this.distributionParameters = distributionParameters;
distributionParameters = ArrayUtility.insert(0, distributionParameters, random);
this.distribution = ReflectionUtility.getInstance(distributionClazz, distributionParameters);
}
示例13
@Override
public void afterLoad() {
try {
random = (RandomGenerator) ReflectionUtility.getInstance(Class.forName(randomClass), randomSeed);
Object[] parameters = ArrayUtility.insert(0, distributionParameters, random);
distribution = (AbstractRealDistribution) ReflectionUtility.getInstance(Class.forName(distributionClass), parameters);
} catch (Exception exception) {
}
}
示例14
@Test
public void testMethod() throws Exception {
ScriptContext context = new ScriptContext();
// 此处故意使用ScriptExpressionTestCase.class,测试是否冲突.
context.useClasses(ScriptFunctionTestCase.class);
ReflectionUtility.doWithLocalMethods(ScriptFunctionTestCase.class, (method) -> {
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) {
context.useMethod(method.getName() + "Method", method);
}
});
ScriptFunction function = getMethodFunction(context);
int number = 10;
Number fibonacci = function.doWith(Number.class, number);
Assert.assertThat(fibonacci.doubleValue(), CoreMatchers.equalTo(fibonacci(number)));
}
示例15
public MethodAccessor(Method method, String name, boolean unique, Comparator comparator) {
ReflectionUtility.makeAccessible(method);
this.method = method;
this.name = name;
this.unique = unique;
this.comparator = comparator;
}
示例16
public FieldAccessor(Field field, String name, boolean unique, Comparator comparator) {
ReflectionUtility.makeAccessible(field);
this.field = field;
this.name = name;
this.unique = unique;
this.comparator = comparator;
}
示例17
@Override
public <E> Iterator<E> iterator(Class<E> clazz, InputStream stream) {
// 实例列表
HashMap<Object, E> instanceObjects = new HashMap<>();
try {
Properties properties = new Properties();
properties.load(stream);
Constructor<E> constructor = clazz.getDeclaredConstructor();
ReflectionUtility.makeAccessible(constructor);
Field storageId = ReflectionUtility.uniqueField(clazz, ResourceId.class);
storageId.setAccessible(true);
TreeMap<?, ?> keyValues = new TreeMap<>(properties);
for (Entry<?, ?> keyValue : keyValues.entrySet()) {
LinkedList<String> fieldNames = new LinkedList<>(Arrays.asList(String.class.cast(keyValue.getKey()).split(dot)));
String fieldName = fieldNames.pollFirst();
String fieldValue = String.class.cast(keyValue.getValue());
Object instanceId = ConversionUtility.convert(fieldName, storageId.getGenericType());
E instanceObject = instanceObjects.get(instanceId);
if (instanceObject == null) {
instanceObject = constructor.newInstance();
storageId.set(instanceObject, instanceId);
instanceObjects.put(instanceId, instanceObject);
}
if (fieldNames.isEmpty()) {
continue;
} else {
fieldName = fieldNames.pollFirst();
process(instanceObject, clazz, fieldName, fieldNames, fieldValue);
}
}
return instanceObjects.values().iterator();
} catch (Exception exception) {
throw new StorageException("遍历Properties异常", exception);
}
}
示例18
/**
* 构造方法
*
* @param metadata
*/
MongoMetadata(Class<?> clazz) {
Document document = clazz.getAnnotation(Document.class);
if (document == null) {
throw new IllegalArgumentException();
}
ormName = document.collection();
if (StringUtility.isBlank(ormName)) {
ormName = clazz.getSimpleName();
ormName = ormName.substring(0, 1).toLowerCase() + ormName.substring(1, ormName.length());
}
ormClass = clazz;
ReflectionUtility.doWithFields(ormClass, (field) -> {
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
return;
}
if (field.isAnnotationPresent(Version.class)) {
versionName = field.getName();
return;
}
Class<?> type = field.getType();
fields.put(field.getName(), type);
if (field.isAnnotationPresent(Id.class)) {
primaryName = field.getName();
primaryClass = type;
}
if (field.isAnnotationPresent(Indexed.class)) {
indexNames.add(field.getName());
}
});
}
示例19
/**
* 构造方法
*
* @param metadata
*/
HibernateMetadata(Class<?> clazz) {
ormClass = clazz;
ormName = clazz.getName();
ReflectionUtility.doWithFields(ormClass, (field) -> {
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
return;
}
if (field.isAnnotationPresent(Version.class)) {
versionName = field.getName();
return;
}
Class<?> type = ClassUtility.primitiveToWrapper(field.getType());
if (String.class == type) {
fields.put(field.getName(), type);
} else if (type.isEnum()) {
fields.put(field.getName(), type);
} else if (Collection.class.isAssignableFrom(type) || type.isArray()) {
fields.put(field.getName(), List.class);
} else if (Date.class.isAssignableFrom(type)) {
fields.put(field.getName(), Date.class);
} else {
fields.put(field.getName(), Map.class);
}
if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) {
primaryName = field.getName();
primaryClass = type;
}
});
Table table = clazz.getAnnotation(Table.class);
if (table != null) {
for (Index index : table.indexes()) {
indexNames.add(index.columnList());
}
}
}
示例20
@Override
public PersistenceElement createInstance(IdentityObject<?> cacheObject) {
// if (cacheObject instanceof ProxyObject) {
// cacheObject = ((ProxyObject) cacheObject).getInstance();
// }
PersistenceElement element = new PersistenceElement(PersistenceOperation.CREATE, cacheObject.getId(), cacheObject);
Exception exception = null;
synchronized (cacheObject) {
T copyInstance = copyInstances.get();
ReflectionUtility.copyInstance(element.getCacheObject(), copyInstance);
Lock writeLock = lock.writeLock();
try {
writeLock.lock();
accessor.createInstance(cacheClass, copyInstance);
createdCount.incrementAndGet();
} catch (Exception throwable) {
String message = StringUtility.format("立即策略[{}]处理元素[{}]时异常", new Object[] { name, element });
LOGGER.error(message, throwable);
exception = throwable;
exceptionCount.incrementAndGet();
} finally {
writeLock.unlock();
}
}
if (monitor != null) {
monitor.notifyOperate(element.getOperation(), element.getCacheId(), element.getCacheObject(), exception);
}
return element;
}
示例21
@Override
public PersistenceElement updateInstance(IdentityObject<?> cacheObject) {
// if (cacheObject instanceof ProxyObject) {
// cacheObject = ((ProxyObject) cacheObject).getInstance();
// }
PersistenceElement element = new PersistenceElement(PersistenceOperation.UPDATE, cacheObject.getId(), cacheObject);
Exception exception = null;
synchronized (cacheObject) {
T copyInstance = copyInstances.get();
ReflectionUtility.copyInstance(element.getCacheObject(), copyInstance);
Lock writeLock = lock.writeLock();
try {
writeLock.lock();
accessor.updateInstance(cacheClass, copyInstance);
updatedCount.incrementAndGet();
} catch (Exception throwable) {
String message = StringUtility.format("立即策略[{}]处理元素[{}]时异常", new Object[] { name, element });
LOGGER.error(message, throwable);
exception = throwable;
exceptionCount.incrementAndGet();
} finally {
writeLock.unlock();
}
}
if (monitor != null) {
monitor.notifyOperate(element.getOperation(), element.getCacheId(), element.getCacheObject(), exception);
}
return element;
}
示例22
/**
* 转换指定类
*
* @param clazz
* @return
* @throws Exception
*/
private Class<?> transformClass(final Class<?> clazz) throws Exception {
CtClass proxyClass = proxyClass(clazz);
proxyCacheFields(clazz, proxyClass);
proxyConstructor(clazz, proxyClass);
ReflectionUtility.doWithMethods(clazz, (method) -> {
CacheChange cacheChange = method.getAnnotation(CacheChange.class);
try {
proxyMethod(clazz, proxyClass, method, cacheChange);
} catch (Exception exception) {
String message = StringUtility.format("缓存类型[{}]转换异常", clazz.getName());
throw new CacheException(message, exception);
}
}, (method) -> {
Class<?>[] classes = DEFAULT_METHODS.get(method.getName());
if (classes != null && Arrays.equals(classes, method.getParameterTypes())) {
return false;
}
if (Modifier.isFinal(method.getModifiers()) || Modifier.isStatic(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())) {
return false;
}
if (method.isSynthetic() && method.getName().equals(METHOD_GET_ID)) {
return false;
}
return true;
});
return proxyClass.toClass();
}
示例23
private void assembleField(Object instance, Field field, Object value) {
ReflectionUtility.makeAccessible(field);
try {
field.set(instance, value);
} catch (Exception exception) {
String message = StringUtility.format("无法装配属性[{}]", field);
LOGGER.error(message);
throw new CacheConfigurationException(message);
}
}
示例24
private static void findDependentClasses(Class<?> clazz, Collection<Class<?>> classes) {
ReflectionUtility.doWithFields(clazz, (field) -> {
if (!classes.contains(field.getGenericType())) {
findDependentClasses(field.getGenericType(), classes);
}
}, (field) -> {
return !(Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()));
});
}
示例25
static SwingAttributeNode getInstance(SwingNode node, String name) {
Container container = node.getComponent();
Map<String, PropertyDescriptor> properties = ReflectionUtility.getPropertyDescriptors(container.getClass());
PropertyDescriptor property = properties.get(name);
SwingAttributeNode instance = new SwingAttributeNode(node, property);
return instance;
}
示例26
static Collection<SwingAttributeNode> getInstances(SwingNode node) {
Container container = node.getComponent();
Map<String, PropertyDescriptor> properties = ReflectionUtility.getPropertyDescriptors(container.getClass());
ArrayList<SwingAttributeNode> instances = new ArrayList<>(properties.size());
for (PropertyDescriptor property : properties.values()) {
instances.add(new SwingAttributeNode(node, property));
}
return instances;
}
示例27
private static final CsvInformation getInformation(Class<?> clazz) {
synchronized (clazz) {
CsvInformation information = INFORMATIONS.get(clazz);
try {
if (information == null) {
CsvConfiguration configuration = clazz.getAnnotation(CsvConfiguration.class);
if (configuration == null || configuration.value().length == 0) {
return null;
}
Constructor<?> constructor = clazz.getDeclaredConstructor();
ReflectionUtility.makeAccessible(constructor);
String[] names = configuration.value();
LinkedList<Field> fields = new LinkedList<>();
for (String name : names) {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
fields.add(field);
}
information = new CsvInformation(constructor, fields.toArray(new Field[fields.size()]));
INFORMATIONS.put(clazz, information);
}
} catch (Exception exception) {
throw new RuntimeException(exception);
}
return information;
}
}
示例28
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
super.prepare(configuration, model, space);
neighborSize = configuration.getInteger("recommender.neighbors.knn.number", 50);
// TODO 设置容量
itemNeighbors = new MathVector[itemSize];
Neighborhood<Integer2FloatKeyValue>[] knns = new Neighborhood[itemSize];
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
knns[itemIndex] = new Neighborhood<>(neighborSize, comparator);
}
// TODO 修改为配置枚举
try {
Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
correlation.calculateCoefficients(scoreMatrix, true, (leftIndex, rightIndex, coefficient) -> {
if (leftIndex == rightIndex) {
return;
}
// 忽略相似度为0的物品
if (coefficient == 0F) {
return;
}
knns[leftIndex].updateNeighbor(new Integer2FloatKeyValue(rightIndex, coefficient));
knns[rightIndex].updateNeighbor(new Integer2FloatKeyValue(leftIndex, coefficient));
});
} catch (Exception exception) {
throw new RuntimeException(exception);
}
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
itemNeighbors[itemIndex] = getNeighborVector(knns[itemIndex].getNeighbors());
}
itemMeans = DenseVector.valueOf(itemSize);
userVectors = new SparseVector[userSize];
for (int userIndex = 0; userIndex < userSize; userIndex++) {
userVectors[userIndex] = scoreMatrix.getRowVector(userIndex);
}
itemVectors = new SparseVector[itemSize];
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
itemVectors[itemIndex] = scoreMatrix.getColumnVector(itemIndex);
}
}
示例29
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
super.prepare(configuration, model, space);
neighborSize = configuration.getInteger("recommender.neighbors.knn.number");
// TODO 设置容量
userNeighbors = new MathVector[userSize];
Neighborhood<Integer2FloatKeyValue>[] knns = new Neighborhood[userSize];
for (int userIndex = 0; userIndex < userSize; userIndex++) {
knns[userIndex] = new Neighborhood<>(neighborSize, comparator);
}
// TODO 修改为配置枚举
try {
Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
correlation.calculateCoefficients(scoreMatrix, false, (leftIndex, rightIndex, coefficient) -> {
if (leftIndex == rightIndex) {
return;
}
// 忽略相似度为0的物品
if (coefficient == 0F) {
return;
}
knns[leftIndex].updateNeighbor(new Integer2FloatKeyValue(rightIndex, coefficient));
knns[rightIndex].updateNeighbor(new Integer2FloatKeyValue(leftIndex, coefficient));
});
} catch (Exception exception) {
throw new RuntimeException(exception);
}
for (int userIndex = 0; userIndex < userSize; userIndex++) {
userNeighbors[userIndex] = getNeighborVector(knns[userIndex].getNeighbors());
}
userMeans = DenseVector.valueOf(userSize);
userVectors = new SparseVector[userSize];
for (int userIndex = 0; userIndex < userSize; userIndex++) {
userVectors[userIndex] = scoreMatrix.getRowVector(userIndex);
}
itemVectors = new SparseVector[itemSize];
for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
itemVectors[itemIndex] = scoreMatrix.getColumnVector(itemIndex);
}
}
示例30
Attribute(Class<?> clazz, int index, String name) throws Exception {
this.index = index;
this.field = ReflectionUtility.findField(clazz, name);
ReflectionUtility.makeAccessible(field);
}