java.lang.reflect.Field Java Examples
The following examples show how to use
java.lang.reflect.Field.
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: ReflectionUtilTest.java From common-utils with GNU General Public License v2.0 | 6 votes |
@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())); }
Example #2
Source File: MaterialNumberPicker.java From MaterialNumberPicker with Apache License 2.0 | 6 votes |
/** * 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; } } }
Example #3
Source File: JDKUtil.java From marshalsec with MIT License | 6 votes |
@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; }
Example #4
Source File: ReflectiveAttribute.java From cqengine with Apache License 2.0 | 6 votes |
/** * 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; }
Example #5
Source File: PlatformInfo.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #6
Source File: TestUtils.java From onetwo with Apache License 2.0 | 6 votes |
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; } } }
Example #7
Source File: FabricReflect.java From bleachhack-1.14 with GNU General Public License v3.0 | 6 votes |
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) {} }
Example #8
Source File: GridDeployment.java From ignite with Apache License 2.0 | 6 votes |
/** * 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; }
Example #9
Source File: EntityHelper.java From azeroth with Apache License 2.0 | 6 votes |
/** * 获取全部的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; }
Example #10
Source File: MainWindow.java From Recaf with MIT License | 6 votes |
/** * @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; }
Example #11
Source File: CertificateLengthValidator.java From credhub with Apache License 2.0 | 6 votes |
@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; }
Example #12
Source File: AuthenticationAthenzTest.java From pulsar with Apache License 2.0 | 6 votes |
@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(); } }
Example #13
Source File: AnnotationExpanderTest.java From super-csv-annotation with Apache License 2.0 | 6 votes |
/** * 繰り返しのアノテーションが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(); } }
Example #14
Source File: LiveEngine.java From netbeans with Apache License 2.0 | 6 votes |
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); }
Example #15
Source File: InfluxDbSenderProviderTest.java From graylog-plugin-metrics-reporter with GNU General Public License v3.0 | 6 votes |
@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()); }
Example #16
Source File: DynamicSubProject.java From DotCi with MIT License | 6 votes |
@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(); }
Example #17
Source File: bug7004134.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
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); } }
Example #18
Source File: DOMNode.java From netbeans with Apache License 2.0 | 6 votes |
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; } }
Example #19
Source File: PojoSerializerSnapshotTest.java From flink with Apache License 2.0 | 6 votes |
@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); }
Example #20
Source File: HttpSSLResponseCodec.java From NetBare with MIT License | 6 votes |
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)); }
Example #21
Source File: YamlDataSourceParameterMerger.java From shardingsphere with Apache License 2.0 | 6 votes |
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; }
Example #22
Source File: PriorityMessageQueueTest.java From qpid-jms with Apache License 2.0 | 6 votes |
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(); } }
Example #23
Source File: JAXRSUtils.java From cxf with Apache License 2.0 | 6 votes |
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; }
Example #24
Source File: CheckAttributedTree.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
@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; }
Example #25
Source File: LineHeightEditText.java From LineHeightEditText with Apache License 2.0 | 5 votes |
private void setTextCursorDrawable() { try { Method method = TextView.class.getDeclaredMethod("createEditorIfNeeded"); method.setAccessible(true); method.invoke(this); Field field1 = TextView.class.getDeclaredField("mEditor"); Field field2 = Class.forName("android.widget.Editor").getDeclaredField("mCursorDrawable"); field1.setAccessible(true); field2.setAccessible(true); Object arr = field2.get(field1.get(this)); Array.set(arr, 0, new LineSpaceCursorDrawable(getCursorColor(), getCursorWidth(), getCursorHeight())); Array.set(arr, 1, new LineSpaceCursorDrawable(getCursorColor(), getCursorWidth(), getCursorHeight())); } catch (Exception ignored) { } }
Example #26
Source File: StepUtils.java From allure-java with Apache License 2.0 | 5 votes |
protected Step extractStep(final StepDefinitionMatch match) { try { final Field step = match.getClass().getDeclaredField("step"); step.setAccessible(true); return (Step) step.get(match); } catch (ReflectiveOperationException e) { //shouldn't ever happen LOG.error(e.getMessage(), e); throw new CucumberException(e); } }
Example #27
Source File: ErrorCollectorExtension.java From p4ic4idea with Apache License 2.0 | 5 votes |
private void inject(Object testInstance, Field field, ExtensionContext extensionContext) { field.setAccessible(true); try { field.set(testInstance, getErrors(extensionContext)); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Example #28
Source File: HueBridgeHandlerOSGiTest.java From smarthome with Eclipse Public License 2.0 | 5 votes |
private void injectBridge(HueBridgeHandler hueBridgeHandler, HueBridge bridge) { try { Field hueBridgeField = hueBridgeHandler.getClass().getDeclaredField("hueBridge"); hueBridgeField.setAccessible(true); hueBridgeField.set(hueBridgeHandler, bridge); } catch (Exception e) { throw new AssertionError(e); } }
Example #29
Source File: JAXBWrapperAccessor.java From hottub with GNU General Public License v2.0 | 5 votes |
static protected PropertySetter createPropertySetter(Field field, Method setter) { if (!field.isAccessible()) { if (setter != null) { MethodSetter injection = new MethodSetter(setter); if (injection.getType().toString().equals(field.getType().toString())) { return injection; } } } return new FieldSetter(field); }
Example #30
Source File: SQLite3Table.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void bind(SQLiteConnection conn, SQLiteStatement stmt, T value) throws Exception { int index = 1; for (Field f : fields.keySet()) { DbUtils.bind(stmt, f.get(value), index++); } }