Java Code Examples for java.lang.reflect.Field#isAccessible()
The following examples show how to use
java.lang.reflect.Field#isAccessible() .
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: ReflectionUtil.java From SonarPet with GNU General Public License v3.0 | 6 votes |
/** * 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; } }
Example 2
Source File: InjectingAnnotationEngine.java From astor with GNU General Public License v2.0 | 6 votes |
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; }
Example 3
Source File: JobProcessManagerImpl.java From genie with Apache License 2.0 | 6 votes |
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; }
Example 4
Source File: GlobalListenerSupport.java From tomee with Apache License 2.0 | 6 votes |
/** * 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); } } } }
Example 5
Source File: HiddenHtmlConfirm.java From ats-framework with Apache License 2.0 | 6 votes |
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); } } }
Example 6
Source File: ReflectUtil.java From BlogManagePlatform with Apache License 2.0 | 6 votes |
/** * 设置目标实体的指定字段的值 * @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 7
Source File: AppUtils.java From LiveEventBus with Apache License 2.0 | 6 votes |
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) { /**/ } } }
Example 8
Source File: TestReflections.java From sarl with Apache License 2.0 | 6 votes |
/** * 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); }
Example 9
Source File: ReflectionUtil.java From EchoPet with GNU General Public License v3.0 | 6 votes |
/** * 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; } }
Example 10
Source File: ServerListener.java From tomee with Apache License 2.0 | 5 votes |
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); } } }
Example 11
Source File: FieldUtils.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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); }
Example 12
Source File: EnhancedRobustUtils.java From Robust with Apache License 2.0 | 5 votes |
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); }
Example 13
Source File: ReflectExtensions.java From xtext-lib with Eclipse Public License 2.0 | 5 votes |
/** * 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); }
Example 14
Source File: SkLearnEncoder.java From jpmml-sklearn with GNU Affero General Public License v3.0 | 5 votes |
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); }
Example 15
Source File: BaseActivity.java From Bailan with Apache License 2.0 | 5 votes |
/** * 解决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(); } } }
Example 16
Source File: ClassUtil.java From j360-dubbo-app-all with Apache License 2.0 | 5 votes |
/** * 改变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); } }
Example 17
Source File: Log4J2LoggerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@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); } }
Example 18
Source File: ReflectionUtils.java From sofa-ark with Apache License 2.0 | 5 votes |
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); } }
Example 19
Source File: FieldUtils.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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); }
Example 20
Source File: ReflectionUtils.java From dolphin with Apache License 2.0 | 3 votes |
/** * 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); } }