Skip to content

Commit

Permalink
added more reflection helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
Sascha Roth committed May 2, 2020
1 parent 00cdcff commit b805a4c
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ allprojects {
2) In your library/build.gradle add:
```groovy
dependencies {
implementation 'com.github.ChickenHook:RestrictionBypass:2.1'
implementation 'com.github.ChickenHook:RestrictionBypass:2.2'
}
```
## Usage
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package org.chickenhook.restrictionbypass;

import org.chickenhook.restrictionbypass.helpers.Reflection;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

public class ReflectionHelperTest {

Object reflectiveField = new Object();
Object reflectiveField;

@Before
public void setUp() {
reflectiveField = new Object();
}

@Test
public void getReflective() throws Exception {
assertSame(Reflection.getReflective(this, "reflectiveField"), reflectiveField);
}

@Test
public void setReflective() throws Exception {
Reflection.setReflective(this, "reflectiveField", null);
assertNull(reflectiveField);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,35 @@ <T> T getReflective(@Nullable Object obj, @NonNull Class<?> cls, @NonNull String
f.setAccessible(true);
return (T) f.get(obj);
}



/**
* Set a member of the given object
* @param obj containing the member
* @param field the member name
* @param value the value to be set
* @throws NoSuchFieldException when field was found
* @throws IllegalAccessException when field was not accessible
*/
public static @Nullable
void setReflective(@NonNull Object obj, @NonNull String field, @Nullable Object value) throws NoSuchFieldException, IllegalAccessException {
setReflective(obj, obj.getClass(), field, value);
}

/**
* Set a member of the given object
* @param obj containing the member
* @param cls super class of the obj
* @param field the member name
* @param value the value to be set
* @throws NoSuchFieldException when field was found
* @throws IllegalAccessException when field was not accessible
*/
public static @Nullable
void setReflective(@Nullable Object obj, @NonNull Class<?> cls, @NonNull String field, @Nullable Object value) throws NoSuchFieldException, IllegalAccessException {
Field f = cls.getDeclaredField(field);
f.setAccessible(true);
f.set(obj, value);
}
}

0 comments on commit b805a4c

Please sign in to comment.