Java Code Examples for java.lang.reflect.Field.set()

The following are Jave code examples for showing how to use set() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: PetBlocks   File: CustomZombie.java   View Source Code Vote up 6 votes
public CustomZombie(Player player, PetBlock petBlock) {
    super(((CraftWorld) player.getWorld()).getHandle());
    this.b(true);
    try {
        final Field bField = PathfinderGoalSelector.class.getDeclaredField("b");
        bField.setAccessible(true);
        final Field cField = PathfinderGoalSelector.class.getDeclaredField("c");
        cField.setAccessible(true);
        bField.set(this.goalSelector, new UnsafeList<PathfinderGoalSelector>());
        bField.set(this.targetSelector, new UnsafeList<PathfinderGoalSelector>());
        cField.set(this.goalSelector, new UnsafeList<PathfinderGoalSelector>());
        cField.set(this.targetSelector, new UnsafeList<PathfinderGoalSelector>());
        this.getAttributeInstance(GenericAttributes.d).setValue(0.30000001192092896D * ConfigPet.getInstance().getModifier_petwalking());
        this.goalSelector.a(0, new PathfinderGoalFloat(this));
        this.goalSelector.a(1, new OwnerPathfinder(this,petBlock));
    } catch (final Exception exc) {
        PetBlocksPlugin.logger().log(Level.WARNING, "EntityNMS exception.", exc);
    }
    this.petBlock = petBlock;
    this.S = (float) ConfigPet.getInstance().getModifier_petclimbing();
}
 
Example 2
Project: CustomWorldGen   File: GradleStart.java   View Source Code Vote up 6 votes
private static void hackNatives()
{
    String paths = System.getProperty("java.library.path");
    String nativesDir = "F:/GradleStore/caches/minecraft/net/minecraft/natives/1.10.2";
    
    if (Strings.isNullOrEmpty(paths))
        paths = nativesDir;
    else
        paths += File.pathSeparator + nativesDir;
    
    System.setProperty("java.library.path", paths);
    
    // hack the classloader now.
    try
    {
        final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
        sysPathsField.setAccessible(true);
        sysPathsField.set(null, null);
    }
    catch(Throwable t) {};
}
 
Example 3
Project: classchecks   File: OpenCV.java   View Source Code Vote up 6 votes
private static void addLibraryDir(String libraryPath) throws Exception {  
    Field userPathsField = ClassLoader.class.getDeclaredField("usr_paths");  
    userPathsField.setAccessible(true);  
    String[] paths = (String[]) userPathsField.get(null);  
    StringBuilder sb = new StringBuilder();  
    for (int i = 0; i < paths.length; i++) {  
        if (libraryPath.equals(paths[i])) {  
            continue;  
        }  
        sb.append(paths[i]).append(';');  
    }  
    sb.append(libraryPath);  
    System.setProperty("java.library.path", sb.toString());  
    final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");  
    sysPathsField.setAccessible(true);  
    sysPathsField.set(null, null);  
}
 
Example 4
Project: Just-Evaluator   File: ReflectUtils.java   View Source Code Vote up 6 votes
/**
 * 设置给定的对象中给定名称的字段的值
 *
 * @param object              给定的对象
 * @param fieldName           要设置的字段的名称
 * @param newValue            要设置的字段的值
 * @param isFindDeclaredField 是否查找Declared字段
 * @param isUpwardFind        如果在当前类中找不到的话,是否取其父类中查找
 * @return 设置是否成功。false:字段不存在或新的值与字段的类型不一样,导致转型失败
 */
public static boolean setField(Object object, String fieldName, Object newValue, boolean isFindDeclaredField, boolean isUpwardFind) {
    boolean result = false;
    Field field = getField(object.getClass(), fieldName, isFindDeclaredField, isUpwardFind);
    if (field != null) {
        try {
            field.setAccessible(true);
            field.set(object, newValue);
            result = true;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            result = false;
        }
    }
    return result;
}
 
Example 5
Project: GitHub   File: TinkerResourcePatcher.java   View Source Code Vote up 6 votes
/**
     * Why must I do these?
     * Resource has mTypedArrayPool field, which just like Message Poll to reduce gc
     * MiuiResource change TypedArray to MiuiTypedArray, but it get string block from offset instead of assetManager
     */
    private static void clearPreloadTypedArrayIssue(Resources resources) {
        // Perform this trick not only in Miui system since we can't predict if any other
        // manufacturer would do the same modification to Android.
//        if (!isMiuiSystem) {
//            return;
//        }
        Log.w(TAG, "try to clear typedArray cache!");
        // Clear typedArray cache.
        try {
            Field typedArrayPoolField = ShareReflectUtil.findField(Resources.class, "mTypedArrayPool");

            final Object origTypedArrayPool = typedArrayPoolField.get(resources);

            Field poolField = ShareReflectUtil.findField(origTypedArrayPool, "mPool");

            final Constructor<?> typedArrayConstructor = origTypedArrayPool.getClass().getConstructor(int.class);
            typedArrayConstructor.setAccessible(true);
            final int poolSize = ((Object[]) poolField.get(origTypedArrayPool)).length;
            final Object newTypedArrayPool = typedArrayConstructor.newInstance(poolSize);
            typedArrayPoolField.set(resources, newTypedArrayPool);
        } catch (Throwable ignored) {
            Log.e(TAG, "clearPreloadTypedArrayIssue failed, ignore error: " + ignored);
        }
    }
 
Example 6
Project: qpp-conversion-tool   File: StorageServiceImplIntegration.java   View Source Code Vote up 6 votes
@Before
public void setup() throws IllegalAccessException, NoSuchFieldException {

	Assume.assumeTrue(System.getProperty("skip.long") == null);
	TestUtils.disableSslCertChecking();

	amazonS3Client = AmazonS3ClientBuilder.standard()
			.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
					LocalstackTestRunner.getEndpointS3(),
					LocalstackTestRunner.getDefaultRegion()))
			.withChunkedEncodingDisabled(true)
			.withPathStyleAccessEnabled(true).build();
	amazonS3Client.createBucket(bucketName);

	S3Config config = new S3Config();

	Field field = StorageServiceImpl.class.getDeclaredField("s3TransferManager");
	field.setAccessible(true);
	field.set(underTest, config.s3TransferManager(amazonS3Client));

	field = StorageServiceImpl.class.getDeclaredField("environment");
	field.setAccessible(true);
	field.set(underTest, environment);
}
 
Example 7
Project: oma-riista-android   File: ViewAnnotations.java   View Source Code Vote up 6 votes
private static void scanIdAnnotations(Object target,  Field f, View view) {
    ViewId viewIds = f.getAnnotation(ViewId.class);
    if (viewIds != null) {
        View targetView = findViewByIds(view, viewIds.value());
        
        if (targetView == null && viewIds.optional()) {
            return;
        }
        else if (!viewIds.optional() && targetView == null) {
            throw new RuntimeException("Mandatory view id not found");
        }
        
        if (!f.isAccessible()) {
            f.setAccessible(true);
        }
        
        try {
            f.set(target, targetView);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 8
Project: Bailan   File: BaseActivity.java   View Source Code Vote up 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 9
Project: stock-api-sdk   File: StockFileLicensePropTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getUrl_should_return_Url_of_Type_String_StockFileLicenseProp()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = prop.getClass().getDeclaredField("mUrl");
    f.setAccessible(true);
    f.set(prop, "www.example.com");
    Assert.assertTrue(prop.getUrl().equals("www.example.com"));
}
 
Example 10
Project: QuantTester   File: ReflectHelper.java   View Source Code Vote up 5 votes
public final static void setPrivateField(final Object obj, final String field_name, final Object value) {
	Field field = getFieldIncludingSuper(obj.getClass(), field_name);
	if (field != null) {
		field.setAccessible(true);
		try {
			field.set(obj, value);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
 
Example 11
Project: stock-api-sdk   File: SearchParametersTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getFilterEditorial_should_return_media_Filter_Editorial_of_Type_Boolean()
        throws NoSuchFieldException,
        IllegalAccessException {
    Assert.assertTrue(param.getFilterEditorial() == null);
    Field f = param.getClass().getDeclaredField("mFilterEditorial");
    f.setAccessible(true);
    f.set(param, true);
    Assert.assertEquals(true, param.getFilterEditorial().booleanValue());
}
 
Example 12
Project: stock-api-sdk   File: StockLicenseHistoryFileTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getCreatorName_should_return_media_CreatorName_ofType_String_StockLicenseHistoryFile()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = stocklicensehistoryfile.getClass().getDeclaredField("mCreatorName");
    f.setAccessible(true);
    f.set(stocklicensehistoryfile, "SomeText");
    Assert.assertTrue(stocklicensehistoryfile.getCreatorName().equals("SomeText"));
}
 
Example 13
Project: StrokeTextView   File: StrokeTextView.java   View Source Code Vote up 5 votes
private void setColor(int color) {
    Field textColorField;
    try {
        textColorField = TextView.class.getDeclaredField("mCurTextColor");
        textColorField.setAccessible(true);
        textColorField.set(this, color);
        textColorField.setAccessible(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
    mPaint.setColor(color);
}
 
Example 14
Project: Recaf   File: OpcodeTypeSwitchPanel.java   View Source Code Vote up 5 votes
/**
 * Update {@link #opcode} value.
 *
 * @param value
 */
private void setValue(int value) {
	try {
		Field op = AbstractInsnNode.class.getDeclaredField("opcode");
		op.setAccessible(true);
		op.set(opcode, value);
		list.repaint();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Project: stock-api-sdk   File: SearchCategoryRequestTest.java   View Source Code Vote up 5 votes
@Test(groups = { "Getters" })
void getCategoryId_should_return_IntegerValue_of_Field_CategoryId()
        throws NoSuchFieldException, IllegalAccessException {
    Field f = request.getClass().getDeclaredField("mCategoryId");
    f.setAccessible(true);
    f.set(request, 1231);
    Assert.assertEquals(1231, request.getCategoryId().intValue());
}
 
Example 16
Project: flexfx   File: UtilityServiceImpl.java   View Source Code Vote up 5 votes
@Override
public final void populateWrapper(final ControllerWrapper wrapper, final String fxmlFile) throws IOException, ClassCastException
{
    final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    try
    {
        Thread.currentThread().setContextClassLoader(wrapper.getControllerClass().getClassLoader());
        final Field controllerField = wrapper.getClass().getDeclaredField(ControllerWrapper.CONTROLLER_FIELD_NAME);
        controllerField.setAccessible(true);
        final Field parentNodeField = wrapper.getClass().getDeclaredField(ControllerWrapper.NODE_FIELD_NAME);
        parentNodeField.setAccessible(true);
        final FXMLLoader loader = new FXMLLoader(wrapper.getControllerClass().getResource(fxmlFile));
        final Parent parentNode = loader.load();
        controllerField.set(wrapper, wrapper.getControllerClass().cast(loader.getController()));
        parentNodeField.set(wrapper, parentNode);
    }
    catch (IllegalAccessException | NoSuchFieldException exception)
    {
        // Safe to capture here as in full control of the ControllerWrapper source and hence field access and
        // field availability. We should never arrive here, at least not in production.
        throw new RuntimeException(exception);
    }
    finally
    {
        Thread.currentThread().setContextClassLoader(ccl);
    }
}
 
Example 17
Project: Bigbang   File: WebActivity.java   View Source Code Vote up 5 votes
private void setConfigCallback(WindowManager paramWindowManager) {
    try {
        Field localField = WebView.class.getDeclaredField("mWebViewCore").getType().getDeclaredField("mBrowserFrame").getType().getDeclaredField("sConfigCallback");
        localField.setAccessible(true);
        Object localObject = localField.get(null);
        if (localObject == null) {
            return;
        }
        localField = localField.getType().getDeclaredField("mWindowManager");
        localField.setAccessible(true);
        localField.set(localObject, paramWindowManager);
        return;
    } catch (Exception ex) {
    }
}
 
Example 18
Project: TherapyGuide   File: AlarmSetterTest.java   View Source Code Vote up 5 votes
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
Project: ViewUtilsNB   File: ViewUtils.java   View Source Code Vote up 4 votes
private static void bindView(Activity activity) {
	/**
	 * 1. 获取Activity的字节码
	 */
	Class<Activity> clazz = (Class<Activity>) activity.getClass();
	/**
	 * 2. 获取字节码中的所有字段
	 */
	Field[] fields = clazz.getDeclaredFields();
	/**
	 * 3. 遍历fields,找出字段上有注解的字段
	 */
	for(Field field : fields){
		/**
		 * 4. 判断field上有没有ViewInject注解对象
		 */
		ViewInject viewInject = field.getAnnotation(ViewInject.class);
		/**
		 * 5. 如果viewInject==null,则不用处理当前字段,否则则需要处理
		 */
		if (viewInject!=null) {
			/**
			 * 6. 获取ViewInject对象的值(resId)
			 */
			int resId = viewInject.value();
			/**
			 * 7. 根据 resId找到对应的控件
			 */
			View view = activity.findViewById(resId);
			
			/**
			 * 8. 设置field可访问(暴力反射)
			 */
			field.setAccessible(true);
			/**
			 * 9. 将控件view设置给field
			 */
			try {
				field.set(activity, view);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 20
Project: treasure   File: FieldUtil.java   View Source Code Vote up 2 votes
/**
 * 设置域的值
 *
 * @param f
 * @param obj
 * @return
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public static Object set(Field f, Object obj, Object value) throws IllegalArgumentException, IllegalAccessException {
    f.setAccessible(true);
    f.set(obj, value);
    return f.get(obj);
}