下面列出了怎么用java.lang.reflect.Field的API类实例代码及写法,或者点击链接到github查看源代码。
private void addIncommingRef (Object to, Object from, Field f) {
// wrap statics with special (private) object
Object save = from != null ? from : Root.createStatic(f, to);
Object entry = objects.get(to);
if (entry == null) {
if (save instanceof Object[]) {
entry= new Object[] { save };
} else {
entry = save;
}
} else if (! (entry instanceof Object[])) {
entry = new Object[] { entry, save };
} else {
int origLen = ((Object[])entry).length;
Object[] ret = new Object[origLen + 1];
System.arraycopy(entry, 0, ret, 0, origLen);
ret[origLen] = save;
entry = ret;
}
objects.put(to, entry);
}
public static void autoFindAndInjectFields(Object inst, Map properties){
Collection<Field> fields = ReflectUtils.findFieldsFilterStatic(inst.getClass());
if(fields==null || fields.isEmpty())
return ;
// Map properties = M.c(objects);
for(Field f :fields){
if(properties.containsKey(f.getName())){
ReflectUtils.setBeanFieldValue(f, inst, properties.get(f.getName()));
continue;
}
if(properties.containsKey(f.getType())){
ReflectUtils.setBeanFieldValue(f, inst, properties.get(f.getType()));
continue;
}
}
}
/**
* Adds a default size for the given jdbc type.
*
* @param jdbcTypeName The name of the jdbc type, one of the {@link Types} constants
* @param defaultSize The default size
*/
public void setDefaultSize(String jdbcTypeName, int defaultSize)
{
try
{
Field constant = Types.class.getField(jdbcTypeName);
if (constant != null)
{
setDefaultSize(constant.getInt(null), defaultSize);
}
}
catch (Exception ex)
{
// ignore -> won't be defined
_log.warn("Cannot add default size for undefined jdbc type "+jdbcTypeName, ex);
}
}
@SuppressWarnings ( {
"rawtypes", "unchecked"
} )
public static TreeMap<Object, Object> makeTreeMap ( Object tgt, Comparator comparator ) throws Exception {
TreeMap<Object, Object> tm = new TreeMap<>(comparator);
Class<?> entryCl = Class.forName("java.util.TreeMap$Entry");
Constructor<?> entryCons = entryCl.getDeclaredConstructor(Object.class, Object.class, entryCl);
entryCons.setAccessible(true);
Field leftF = Reflections.getField(entryCl, "left");
Field rootF = Reflections.getField(TreeMap.class, "root");
Object root = entryCons.newInstance(tgt, tgt, null);
leftF.set(root, entryCons.newInstance(tgt, tgt, root));
rootF.set(tm, root);
Reflections.setFieldValue(tm, "size", 2);
return tm;
}
/**
* Uses reflection to access divider private attribute and override its color
* Use Color.Transparent if you wish to hide them
*/
public void setSeparatorColor(int separatorColor) {
mSeparatorColor = separatorColor;
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try {
pf.set(this, new ColorDrawable(separatorColor));
} catch (IllegalAccessException | IllegalArgumentException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* Gets all entries from the specified class or its super-classes that have
* been annotated with annotation provided.
*
* @param cls Class in which search for methods.
* @param annCls Annotation.
* @return Set of entries with given annotations.
*/
private Iterable<Field> fieldsWithAnnotation(Class<?> cls, Class<? extends Annotation> annCls) {
assert cls != null;
assert annCls != null;
Collection<Field> fields = fieldsFromCache(cls, annCls);
if (fields == null) {
fields = new ArrayList<>();
for (Field field : cls.getDeclaredFields()) {
Annotation ann = field.getAnnotation(annCls);
if (ann != null || needsRecursion(field))
fields.add(field);
}
cacheFields(cls, annCls, fields);
}
return fields;
}
/**
* @param controller
* Window context.
*
* @return main window instance.
*/
public static MainWindow get(GuiController controller) {
if(window == null) {
MainWindow app = window = new MainWindow(controller);
PlatformImpl.startup(() -> {
Stage stage = new Stage();
try {
Field field = Stage.class.getDeclaredField("primary");
field.setAccessible(true);
field.setBoolean(stage, true);
app.init();
app.start(stage);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
// Disable CSS logger, it complains a lot about non-issues
try {
ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class)
.setLoggerLevel("javafx.css", "OFF");
} catch (IllegalArgumentException ignored) {
// Expected: logger may not exist
}
});
}
return window;
}
@Override
public void scan(JCTree tree) {
if (tree == null ||
excludeTags.contains(treeUtil.nameFromTag(tree.getTag()))) {
return;
}
Info self = new Info(tree, endPosTable);
if (mandatoryType(tree)) {
check(tree.type != null,
"'null' field 'type' found in tree ", self);
if (tree.type==null)
new Throwable().printStackTrace();
}
Field errField = checkFields(tree);
if (errField!=null) {
check(false,
"'null' field '" + errField.getName() + "' found in tree ", self);
}
Info prevEncl = encl;
encl = self;
tree.accept(this);
encl = prevEncl;
}
/**
* 繰り返しのアノテーションが1つの場合の展開
*/
@Test
public void testExpand_repeatSingle() {
Field field = getSampleField("repeatSingle");
Annotation targetAnno = field.getAnnotation(CsvLengthMax.class);
List<ExpandedAnnotation> actual = expander.expand(targetAnno);
assertThat(actual).hasSize(1);
{
ExpandedAnnotation expandedAnno = actual.get(0);
assertThat(expandedAnno.getOriginal()).isInstanceOf(CsvLengthMax.class);
assertThat(expandedAnno.getIndex()).isEqualTo(0);
assertThat(expandedAnno.isComposed()).isEqualTo(false);
assertThat(expandedAnno.getChilds()).isEmpty();
}
}
private static boolean isDefaultValue(final Field field, final Object value) {
Class<?> clazz = field.getType();
if (int.class.equals(clazz) || Integer.class.equals(clazz)) {
return (int) value == 0;
} else if (byte.class.equals(clazz) || Byte.class.equals(clazz)) {
return (byte) value == 0;
} else if (long.class.equals(clazz) || Long.class.equals(clazz)) {
return (long) value == 0L;
} else if (double.class.equals(clazz) || Double.class.equals(clazz)) {
return (double) value == 0.0d;
} else if (float.class.equals(clazz) || Float.class.equals(clazz)) {
return (float) value == 0.0f;
} else if (short.class.equals(clazz) || Short.class.equals(clazz)) {
return (short) value == 0;
} else if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {
return !((boolean) value);
} else if (String.class.equals(clazz)) {
return null == value || "".equals(value);
}
return false;
}
private void enableOpenSSLEngineImplAlpn() throws NoSuchFieldException, IllegalAccessException {
Field sslParametersField = mSSLEngine.getClass().getDeclaredField("sslParameters");
sslParametersField.setAccessible(true);
Object sslParameters = sslParametersField.get(mSSLEngine);
if (sslParameters == null) {
throw new IllegalAccessException("sslParameters value is null");
}
Field useSessionTicketsField = sslParameters.getClass().getDeclaredField("useSessionTickets");
useSessionTicketsField.setAccessible(true);
useSessionTicketsField.set(sslParameters, true);
Field useSniField = sslParameters.getClass().getDeclaredField("useSni");
useSniField.setAccessible(true);
useSniField.set(sslParameters, true);
Field alpnProtocolsField = sslParameters.getClass().getDeclaredField("alpnProtocols");
alpnProtocolsField.setAccessible(true);
alpnProtocolsField.set(sslParameters, concatLengthPrefixed(mClientAlpns));
}
@Test
public void testRestoreSerializerWithSameFields() {
final PojoSerializerSnapshot<TestPojo> testSnapshot = buildTestSnapshot(Arrays.asList(
ID_FIELD,
NAME_FIELD,
HEIGHT_FIELD
));
final TypeSerializer<TestPojo> restoredSerializer = testSnapshot.restoreSerializer();
assertSame(restoredSerializer.getClass(), PojoSerializer.class);
final PojoSerializer<TestPojo> restoredPojoSerializer = (PojoSerializer<TestPojo>) restoredSerializer;
final Field[] restoredFields = restoredPojoSerializer.getFields();
assertArrayEquals(
new Field[] { ID_FIELD.field, NAME_FIELD.field, HEIGHT_FIELD.field },
restoredFields);
final TypeSerializer<?>[] restoredFieldSerializers = restoredPojoSerializer.getFieldSerializers();
assertArrayEquals(
new TypeSerializer[] { IntSerializer.INSTANCE, StringSerializer.INSTANCE, DoubleSerializer.INSTANCE },
restoredFieldSerializers);
}
@Override
public void onLoad(final ItemGroup<? extends Item> parent, final String name) throws IOException {
try {
final Field parentField = AbstractItem.class.getDeclaredField("parent");
parentField.setAccessible(true);
ReflectionUtils.setField(parentField, this, parent);
} catch (final Exception e) {
throw new RuntimeException(e);
}
doSetName(name);
if (this.transientActions == null) {
this.transientActions = new Vector<>();
}
updateTransientActions();
getBuildersList().setOwner(this);
getPublishersList().setOwner(this);
getBuildWrappersList().setOwner(this);
initRepos();
}
@Test
public void getRowType() throws Exception {
Field f1 = BaseClass.class.getField("f1");
Field f2 = BaseClass.class.getField("f2");
Field f3 = BaseClass.class.getField("f3");
Field f4 = ConcreteClass.class.getField("f4");
Field f5 = ConcreteClass.class.getField("f5");
Field array1 = BaseClass.class.getField("array1");
assertEquals(String.class, ReflectionUtil.getRawType(f1.getGenericType(), ConcreteClass.class));
assertEquals(Integer.class, ReflectionUtil.getRawType(f2.getGenericType(), ConcreteClass.class));
assertEquals(String.class, ReflectionUtil.getRawType(f3.getGenericType(), ConcreteClass.class));
assertEquals(Long.class, ReflectionUtil.getRawType(f4.getGenericType(), ConcreteClass.class));
assertEquals(List.class, ReflectionUtil.getRawType(f5.getGenericType(), ConcreteClass.class));
assertEquals(String[].class, ReflectionUtil.getRawType(array1.getGenericType(), ConcreteClass.class));
assertEquals(Object.class, ReflectionUtil.getRawType(f1.getGenericType()));
}
@Test
public void getCreatesSenderWithCorrectDatabaseName() throws Exception {
final MetricsInfluxDbReporterConfiguration configuration = new MetricsInfluxDbReporterConfiguration() {
@Override
public URI getUri() {
return URI.create("udp://127.0.0.1:8086/data_base_1");
}
};
final InfluxDbSenderProvider provider = new InfluxDbSenderProvider(configuration);
final InfluxDbSender influxDbSender = provider.get();
final Field field = Class.forName("com.izettle.metrics.influxdb.InfluxDbBaseSender").getDeclaredField("influxDbWriteObject");
field.setAccessible(true);
final InfluxDbWriteObject influxDbWriteObject = (InfluxDbWriteObject) field.get(influxDbSender);
assertEquals("data_base_1", influxDbWriteObject.getDatabase());
}
private static Component getTipWindow() {
try {
Field tipWindowField = ToolTipManager.class.getDeclaredField("tipWindow");
tipWindowField.setAccessible(true);
Popup value = (Popup) tipWindowField.get(ToolTipManager.sharedInstance());
Field componentField = Popup.class.getDeclaredField("component");
componentField.setAccessible(true);
return (Component) componentField.get(value);
} catch (Exception e) {
throw new RuntimeException("getToolTipComponent failed", e);
}
}
private static String tryGetID(org.openide.nodes.Node node) {
// TODO: Request API to be able to access org.netbeans.modules.html.navigator.Description from the Node's lookup
// Reading attributes from HTMLElementNode
try {
Field sourceField = node.getClass().getDeclaredField("source");
sourceField.setAccessible(true);
Object source = sourceField.get(node);
Method getAttributes = source.getClass().getDeclaredMethod("getAttributes");
getAttributes.setAccessible(true);
Object attributesObj = getAttributes.invoke(source);
Map<String, String> attributes = (Map<String, String>) attributesObj;
return attributes.get("id");
} catch (Exception ex) {
LOG.log(Level.INFO, "Problem while getting id from node "+node+", class = "+node.getClass()+": "+ex.toString());
return null;
}
}
private void singalQueue(PriorityMessageQueue queue) throws Exception {
Field lock = null;
Class<?> queueType = queue.getClass();
while (queueType != null && lock == null) {
try {
lock = queueType.getDeclaredField("lock");
} catch (NoSuchFieldException error) {
queueType = queueType.getSuperclass();
if (Object.class.equals(queueType)) {
queueType = null;
}
}
}
assertNotNull("MessageQueue implementation unknown", lock);
lock.setAccessible(true);
Object lockView = lock.get(queue);
synchronized (lockView) {
lockView.notify();
}
}
public static Response copyResponseIfNeeded(Response response) {
if (!(response instanceof ResponseImpl)) {
Response r = fromResponse(response).build();
Field[] declaredFields = ReflectionUtil.getDeclaredFields(response.getClass());
for (Field f : declaredFields) {
Class<?> declClass = f.getType();
if (declClass == Annotation[].class) {
try {
Annotation[] fieldAnnotations =
ReflectionUtil.accessDeclaredField(f, response, Annotation[].class);
((ResponseImpl)r).setEntityAnnotations(fieldAnnotations);
} catch (Throwable ex) {
LOG.warning("Custom annotations if any can not be copied");
}
break;
}
}
return r;
}
return response;
}
@Test
public void testLoadPrivateKeyBase64() throws Exception {
try {
String paramsStr = new String(Files.readAllBytes(Paths.get("./src/test/resources/authParams.json")));
// load privatekey and encode it using base64
ObjectMapper jsonMapper = ObjectMapperFactory.create();
Map<String, String> authParamsMap = jsonMapper.readValue(paramsStr,
new TypeReference<HashMap<String, String>>() {
});
String privateKeyContents = new String(Files.readAllBytes(Paths.get(authParamsMap.get("privateKey"))));
authParamsMap.put("privateKey", "data:application/x-pem-file;base64,"
+ new String(Base64.getEncoder().encode(privateKeyContents.getBytes())));
AuthenticationAthenz authBase64 = new AuthenticationAthenz();
authBase64.configure(jsonMapper.writeValueAsString(authParamsMap));
PrivateKey privateKey = Crypto.loadPrivateKey(new File("./src/test/resources/tenant_private.pem"));
Field field = authBase64.getClass().getDeclaredField("privateKey");
field.setAccessible(true);
PrivateKey key = (PrivateKey) field.get(authBase64);
assertEquals(key, privateKey);
} catch (Exception e) {
Assert.fail();
}
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
for (final String fieldName : fields) {
try {
final Field field = value.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
if (StringUtils.isEmpty((String) field.get(value))) {
return true;
}
final String certificate = (String) field.get(value);
if (certificate.getBytes(UTF_8).length > 7000) {
return false;
}
} catch (final NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return true;
}
/**
* 获取全部的Field
*
* @param entityClass
* @param fieldList
* @return
*/
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
if (fieldList == null) {
fieldList = new ArrayList<Field>();
}
if (entityClass.equals(Object.class)) {
return fieldList;
}
Field[] fields = entityClass.getDeclaredFields();
for (Field field : fields) {
// 排除静态字段
if (!Modifier.isStatic(field.getModifiers())) {
fieldList.add(field);
}
}
Class<?> superClass = entityClass.getSuperclass();
if (superClass != null && !superClass.equals(Object.class)
&& (!Map.class.isAssignableFrom(superClass)
&& !Collection.class.isAssignableFrom(superClass))) {
return getAllField(entityClass.getSuperclass(), fieldList);
}
return fieldList;
}
/**
* Creates an attribute which reads values from the field indicated using reflection.
*
* @param objectType The type of the object containing the field
* @param fieldType The type of the field in the object
* @param fieldName The name of the field
*/
public ReflectiveAttribute(Class<O> objectType, Class<A> fieldType, String fieldName) {
super(objectType, fieldType, fieldName);
Field field;
try {
field = getField(objectType, fieldName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
}
catch (Exception e) {
throw new IllegalStateException("Invalid attribute definition: No such field '" + fieldName + "' in object '" + objectType.getName() + "'");
}
if (!fieldType.isAssignableFrom(field.getType())) {
throw new IllegalStateException("Invalid attribute definition: The type of field '" + fieldName + "', type '" + field.getType() + "', in object '" + objectType.getName() + "', is not assignable to the type indicated: " + fieldType.getName());
}
this.field = field;
}
public static void writeField(final Object target, final Object value, String obfName, String deobfName) {
if (target == null) return;
final Class<?> cls = target.getClass();
final Field field = getField(cls, obfName, deobfName);
if (field == null) return;
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
field.set(target, value);
} catch (Exception e) {}
}
private <T extends PageObject> void tryToWaitOnPageObjectsVisibility(T pageInstance, Field field) {
try {
waitOnPageObjectsVisibility(pageInstance, field);
} catch (TimeoutException e) {
throw exception(pageInstance, e).whenWaitingForVisibilityOfPageObjectField(field);
}
}
private Field getField(Class<?> clazz, String name) {
try {
return clazz.getField(name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected Result validDeleteTx(int chainId, DeleteContractTransaction tx) {
try {
DeleteContractTxValidator validator = new DeleteContractTxValidator();
Field field = DeleteContractTxValidator.class.getDeclaredField("contractHelper");
field.setAccessible(true);
field.set(validator, contractHelper);
return validator.validate(chainId, tx);
} catch (Exception e) {
Log.error(e);
return getFailed();
}
}
/**
* 初始化组件列表
*/
private void initComponents() throws InstantiationException, IllegalAccessException {
// 获取需要扫描的包名
String pkgName = getPackage();
// 获取包下所有类
List<Class<?>> classes = ClassUtil.getClasses(pkgName);
if (CollectionUtils.isEmpty(classes)) {
return;
}
// 遍历类
for (Class clazz : classes) {
Field[] fields = clazz.getDeclaredFields();
if (fields==null || fields.length==0) {
continue;
}
// 遍历成员变量
for (Field field : fields) {
// 获取Field上的@InjectComponents注解
InjectComponents injectComponents = AnnotationUtil.getAnnotationValueByField(field, InjectComponents.class);
if (injectComponents == null) {
continue;
}
// 创建componentList对象
List<BaseComponent> componentList = initComponentList(injectComponents);
// 赋值
setValueForField(clazz, field, componentList);
}
}
}
public static final Field findFieldIfExists(Class clazz, String fieldName) {
if (clazz == null) {
return null;
}
Field field = null;
try {
field = clazz.getField(fieldName);
} catch (Error | Exception e) {
}
return field;
}
@Test
public void testGetValeOfAPrivateFieldUsingFieldObject() throws Exception {
// GIVEN
privateField = 10l;
final Field toi = getClass().getDeclaredField("privateField");
// WHEN
final Object value = ReflectionUtils.getValue(this, toi);
// THEN
assertThat(privateField, equalTo(value));
}