Skip to content

Commit

Permalink
Allow creation of R from a class for static reference
Browse files Browse the repository at this point in the history
  • Loading branch information
MrNavaStar committed Aug 17, 2024
1 parent c0e25b8 commit 770458a
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/main/java/me/mrnavastar/r/R.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,26 @@
public class R {

private final Object instance;
private final Class<?> clazz;

public R(Object instance) {
this.instance = instance;
clazz = instance.getClass();
}

public R(Class<?> clazz) {
instance = null;
this.clazz = clazz;
}

public static R of(Object instance) {
return new R(instance);
}

public static R of(Class<?> clazz) {
return new R(clazz);
}

// Search super classes for field
private Field findField(Class<?> clazz, String name) throws NoSuchFieldException {
if (clazz == null) throw new NoSuchFieldException();
Expand Down Expand Up @@ -47,15 +58,15 @@ private Method findMethod(Class<?> clazz, String name, Class<?>[] argTypes) thro

public <T> T get(String name, Class<T> type) {
try {
return type.cast(findField(instance.getClass(), name).get(instance));
return type.cast(findField(clazz, name).get(instance));
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}

public void set(String name, Object value) {
try {
findField(instance.getClass(), name).set(instance, value);
findField(clazz, name).set(instance, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
Expand All @@ -64,7 +75,7 @@ public void set(String name, Object value) {
public <T> T call(String name, Class<T> returnType, Object... args) {
try {
Class<?>[] classes = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
Object returnVal = findMethod(instance.getClass(), name, classes).invoke(instance, args);
Object returnVal = findMethod(clazz, name, classes).invoke(instance, args);
if (returnVal == null || returnType == null) return null;
return returnType.cast(returnVal);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
Expand Down

0 comments on commit 770458a

Please sign in to comment.