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

The following examples show how to use java.lang.reflect.Field#setInt() . 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: AtlasJanusGraphDatabase.java    From atlas with Apache License 2.0 6 votes vote down vote up
private static void addSolr6Index() {
    try {
        Field field = StandardIndexProvider.class.getDeclaredField("ALL_MANAGER_CLASSES");
        field.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        Map<String, String> customMap = new HashMap<>(StandardIndexProvider.getAllProviderClasses());
        customMap.put("solr", Solr6Index.class.getName());
        ImmutableMap<String, String> immap = ImmutableMap.copyOf(customMap);
        field.set(null, immap);

        LOG.debug("Injected solr6 index - {}", Solr6Index.class.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: DebugUtilsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static <T> boolean setStaticValue(Class<?> clazz, String filedName, T newValue) {
  try {
    Field field = clazz.getField(filedName);
    field.setAccessible(true);

    /* 去除final修饰符的影响,将字段设为可修改的 */
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);

    return true;
  } catch (Exception e) {
    logger.error(e.getMessage(), e);
    return false;
  }

}
 
Example 3
Source File: NativeCacheManipulatingResolver.java    From Dream-Catcher with MIT License 6 votes vote down vote up
@Override
public void setPositiveDNSCacheTimeout(int timeout, TimeUnit timeUnit) {
    try {
        Class<?> inetAddressCachePolicyClass = Class.forName("sun.net.InetAddressCachePolicy");

        Field positiveCacheTimeoutSeconds = inetAddressCachePolicyClass.getDeclaredField("cachePolicy");
        positiveCacheTimeoutSeconds.setAccessible(true);

        if (timeout < 0) {
            positiveCacheTimeoutSeconds.setInt(null, -1);
            java.security.Security.setProperty("networkaddress.cache.ttl", "-1");
        } else {
            positiveCacheTimeoutSeconds.setInt(null, (int) TimeUnit.SECONDS.convert(timeout, timeUnit));
            java.security.Security.setProperty("networkaddress.cache.ttl", Long.toString(TimeUnit.SECONDS.convert(timeout, timeUnit)));
        }
    } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
        log.warn("Unable to modify native JVM DNS cache timeouts", e);
    }
}
 
Example 4
Source File: Items.java    From BaseMetals with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Uses reflection to expand the size of the combat damage and attack speed arrays to prevent initialization
 * index-out-of-bounds errors
 * @param itemClass The class to modify
 */
private static void expandCombatArrays(Class itemClass) throws IllegalAccessException, NoSuchFieldException {
    // WARNING: this method contains black magic
    final int expandedSize = 256;
    Field[] fields = itemClass.getDeclaredFields();
    for(Field f : fields){
        if(Modifier.isStatic(f.getModifiers())
                && f.getType().isArray()
                && f.getType().getComponentType().equals(float.class)){
            FMLLog.info("%s: Expanding array variable %s.%s to size %s", Thread.currentThread().getStackTrace()[0], itemClass.getSimpleName(), f.getName(), expandedSize);
            f.setAccessible(true); // bypass 'private' key word
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); // bypass 'final' key word
            float[] newArray = new float[expandedSize];
            Arrays.fill(newArray,0F);
            System.arraycopy(f.get(null),0,newArray,0, Array.getLength(f.get(null)));
            f.set(null,newArray);
        }
    }
}
 
Example 5
Source File: PaddedListView.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
@Override
public void setFastScrollEnabled(boolean enabled) {
	super.setFastScrollEnabled(enabled);
	if (enabled && !fastScrollModified) {
		Object fastScroll = getFastScroll();
		if (fastScroll != null) {
			fastScrollModified = true;
			try {
				Field field = fastScroll.getClass().getDeclaredField("mMinimumTouchTarget");
				field.setAccessible(true);
				field.setInt(fastScroll, field.getInt(fastScroll) / 3);
			} catch (Exception e) {
				// Reflective operation, ignore exception
			}
		}
	}
}
 
Example 6
Source File: ReflectionUtil.java    From Bukkit-SSHD with Apache License 2.0 6 votes vote down vote up
public static void setProtectedValue(Class c, Object o, String field, Object newValue) {
    try {

        Field f = c.getDeclaredField(field);

        f.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);

        f.set(o, newValue);
    } catch (NoSuchFieldException | IllegalAccessException ex) {
        System.out.println("*** " + c.getName() + ":" + ex);
    }
}
 
Example 7
Source File: InvokeField.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws NoSuchFieldException,
        SecurityException, IllegalArgumentException, IllegalAccessException {
    Man man = new Man();
    Class<?> claz = man.getClass();
    
    log("==========设置public字段的值==========");
    log("height的值:%d", man.height);
    Field field = claz.getField("height");
    field.setInt(man, 175);
    log("height的值:%d", man.height);
    
    log("==========设置private字段的值==========");
    log("power的值:%d", man.getPower());
    field = claz.getDeclaredField("power");
    field.setAccessible(true);
    field.setInt(man, 100);
    log("power的值:%d", man.getPower());
    
    log("==========获取private字段的值==========");
    int power = field.getInt(man);
    log("power的值:%d", power);
}
 
Example 8
Source File: StatusLoggerTest.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws IOException, NoSuchFieldException, IllegalAccessException {
    statusLogger = Mockito.spy(new StatusLogger());

    logger = Mockito.mock(Logger.class);
    queryableStatusAggregator = Mockito.mock(QueryableStatusAggregator.class);
    flowStatusReport = Mockito.mock(FlowStatusReport.class);

    Mockito.when(flowStatusReport.toString()).thenReturn(MOCK_STATUS);

    Field field = StatusLogger.class.getDeclaredField("logger");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, logger);


    Mockito.when(queryableStatusAggregator.statusReport(MOCK_QUERY)).thenReturn(flowStatusReport);
}
 
Example 9
Source File: TestUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public static void setEnvironmentVariables(Map<String, String> vars) {
  // Setting the environment variables after the JVM has started requires a bit of a hack:
  // we reach into the package-private java.lang.ProcessEnvironment class, which incidentally
  // is platform-specific, and replace the map held in a static final field there,
  // using yet more reflection.
  //
  // This is copied from {#see com.google.apphosting.runtime.NullSandboxPlugin}
  Map<String, String> allVars = new HashMap<>(System.getenv());
  allVars.putAll(vars);
  try {
    Class<?> pe = Class.forName("java.lang.ProcessEnvironment", true, null);
    Field f = pe.getDeclaredField("theUnmodifiableEnvironment");
    f.setAccessible(true);
    Field m = Field.class.getDeclaredField("modifiers");
    m.setAccessible(true);
    m.setInt(f, m.getInt(f) & ~Modifier.FINAL);
    f.set(null, Collections.unmodifiableMap(allVars));
  } catch (ReflectiveOperationException e) {
    throw new RuntimeException("failed to set the environment variables", e);
  }
}
 
Example 10
Source File: NativeCacheManipulatingResolver.java    From Dream-Catcher with MIT License 6 votes vote down vote up
@Override
public void setNegativeDNSCacheTimeout(int timeout, TimeUnit timeUnit) {
    try {
        Class<?> inetAddressCachePolicyClass = Class.forName("sun.net.InetAddressCachePolicy");

        Field negativeCacheTimeoutSeconds = inetAddressCachePolicyClass.getDeclaredField("negativeCachePolicy");
        negativeCacheTimeoutSeconds.setAccessible(true);

        if (timeout < 0) {
            negativeCacheTimeoutSeconds.setInt(null, -1);
            java.security.Security.setProperty("networkaddress.cache.negative.ttl", "-1");
        } else {
            negativeCacheTimeoutSeconds.setInt(null, (int) TimeUnit.SECONDS.convert(timeout, timeUnit));
            java.security.Security.setProperty("networkaddress.cache.negative.ttl", Long.toString(TimeUnit.SECONDS.convert(timeout, timeUnit)));
        }
    } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
        log.warn("Unable to modify native JVM DNS cache timeouts", e);
    }
}
 
Example 11
Source File: Utils.java    From tup.dota2recipe with Apache License 2.0 5 votes vote down vote up
/**
 * FROM FlymeAPI.Lib
 * 
 * 设置状态栏图标为深色和魅族特定的文字风格
 * 
 * @param window
 *            需要设置的窗口
 * @param dark
 *            是否把状态栏颜色设置为深色
 * @return boolean 成功执行返回true
 */
public static boolean setStatusBarDarkIcon(Window window, boolean dark) {
    boolean result = false;
    if (window != null) {
        try {
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
            result = true;
        } catch (Exception e) {
            Log.e(TAG, "setStatusBarDarkIcon: failed");
        }
    }
    return result;
}
 
Example 12
Source File: TestUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static void setFinalField(Field field, Object instance, Object newValue) throws Exception {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(instance, newValue);
}
 
Example 13
Source File: DefaultRequestProcessorTest.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
private static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}
 
Example 14
Source File: MessageBirdServiceImpl.java    From java-rest-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * By default, HttpURLConnection does not support PATCH requests. We can
 * however work around this with reflection. Many thanks to okutane on
 * StackOverflow: https://stackoverflow.com/a/46323891/3521243.
 */
private synchronized static void allowPatchRequestsIfNeeded() throws GeneralException {
    if (isPatchRequestAllowed) {
        // Don't do anything if we've run this method before. We're in a
        // synchronized block, so return ASAP.
        return;
    }

    try {
        // Ensure we can access the fields we need to set.
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
        methodsField.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
        
        Object noInstanceBecauseStaticField = null;
        
        // Determine what methods should be allowed.
        String[] existingMethods = (String[]) methodsField.get(noInstanceBecauseStaticField);
        String[] allowedMethods = getAllowedMethods(existingMethods);
        
        // Override the actual field to allow PATCH.
        methodsField.set(noInstanceBecauseStaticField, allowedMethods);

        // Set flag so we only have to run this once.
        isPatchRequestAllowed = true;
    } catch (IllegalAccessException | NoSuchFieldException e) {
        throw new GeneralException(CAN_NOT_ALLOW_PATCH);
    }
}
 
Example 15
Source File: AncientDataMotionStrategyTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void replaceVmwareCreateCloneFullField() throws Exception {
    Field field = CapacityManager.class.getDeclaredField("VmwareCreateCloneFull");
    field.setAccessible(true);
    // remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, vmwareKey);
}
 
Example 16
Source File: StatusBarUtil.java    From imsdk-android with MIT License 5 votes vote down vote up
/**
 * 设置状态栏图标为深色和魅族特定的文字风格
 * 可以用来判断是否为Flyme用户
 *
 * @param window 需要设置的窗口
 * @param dark  是否把状态栏字体及图标颜色设置为深色
 * @return boolean 成功执行返回true
 */
public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
    boolean result = false;
    if (window != null) {
        try {
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
            result = true;
        } catch (Exception e) {
            return false;
        }
    }
    return result;
}
 
Example 17
Source File: CollectionsDeserializationBenchmark.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
 * setting object values by reflection. We should strive to reduce the discrepancy between this
 * and {@link #timeCollectionsDefault(int)} .
 */
public void timeCollectionsReflectionStreaming(int reps) throws Exception {
  for (int i=0; i<reps; ++i) {
    StringReader reader = new StringReader(json);
    JsonReader jr = new JsonReader(reader);
    jr.beginArray();
    List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>();
    while(jr.hasNext()) {
      jr.beginObject();
      BagOfPrimitives bag = new BagOfPrimitives();
      while(jr.hasNext()) {
        String name = jr.nextName();
        for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
          if (field.getName().equals(name)) {
            Class<?> fieldType = field.getType();
            if (fieldType.equals(long.class)) {
              field.setLong(bag, jr.nextLong());
            } else if (fieldType.equals(int.class)) {
              field.setInt(bag, jr.nextInt());
            } else if (fieldType.equals(boolean.class)) {
              field.setBoolean(bag, jr.nextBoolean());
            } else if (fieldType.equals(String.class)) {
              field.set(bag, jr.nextString());
            } else {
              throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
            }
          }
        }
      }
      jr.endObject();
      bags.add(bag);
    }
    jr.endArray();
  }
}
 
Example 18
Source File: BillingServiceBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
private static void setFinalStatic(Field field, Object newValue)
        throws Exception {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}
 
Example 19
Source File: BGAViewPager.java    From KUtils with Apache License 2.0 4 votes vote down vote up
@Override
public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) {
    /**
     继承ViewPager,重写setPageTransformer方法,移除版本限制,通过反射设置参数和方法

     getDeclaredMethod*()获取的是【类自身】声明的所有方法,包含public、protected和private方法。
     getMethod*()获取的是类的所有共有方法,这就包括自身的所有【public方法】,和从基类继承的、从接口实现的所有【public方法】。

     getDeclaredField获取的是【类自身】声明的所有字段,包含public、protected和private字段。
     getField获取的是类的所有共有字段,这就包括自身的所有【public字段】,和从基类继承的、从接口实现的所有【public字段】。
     */
    Class viewpagerClass = ViewPager.class;

    try {
        boolean hasTransformer = transformer != null;

        Field pageTransformerField = viewpagerClass.getDeclaredField("mPageTransformer");
        pageTransformerField.setAccessible(true);
        PageTransformer mPageTransformer = (PageTransformer) pageTransformerField.get(this);

        boolean needsPopulate = hasTransformer != (mPageTransformer != null);
        pageTransformerField.set(this, transformer);

        Method setChildrenDrawingOrderEnabledCompatMethod = viewpagerClass.getDeclaredMethod("setChildrenDrawingOrderEnabledCompat", boolean.class);
        setChildrenDrawingOrderEnabledCompatMethod.setAccessible(true);
        setChildrenDrawingOrderEnabledCompatMethod.invoke(this, hasTransformer);

        Field drawingOrderField = viewpagerClass.getDeclaredField("mDrawingOrder");
        drawingOrderField.setAccessible(true);
        if (hasTransformer) {
            drawingOrderField.setInt(this, reverseDrawingOrder ? 2 : 1);
        } else {
            drawingOrderField.setInt(this, 0);
        }

        if (needsPopulate) {
            Method populateMethod = viewpagerClass.getDeclaredMethod("populate");
            populateMethod.setAccessible(true);
            populateMethod.invoke(this);
        }
    } catch (Exception e) {
    }
}
 
Example 20
Source File: Config.java    From FastAsyncWorldedit with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Set some field to be accesible
 *
 * @param field
 * @throws NoSuchFieldException
 * @throws IllegalAccessException
 */
private void setAccessible(Field field) throws NoSuchFieldException, IllegalAccessException {
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
}