Skip to content

Instantly share code, notes, and snippets.

@thypon thypon/gist:8476260
Created Jan 17, 2014

Embed
What would you like to do?
I Need Dynamics
import lombok.NonNull;
import java.lang.reflect.Method;
public class Dynamics {
@SuppressWarnings("unchecked")
public static <T> T send(
@NonNull final Class<?> clazz,
@NonNull final String method,
final Object... args) {
int arguments = args.length;
Class[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
try {
return (T)getMethod(clazz, method, parameterTypes).invoke(null, args);
} catch (Exception e) {
throw SneakyException.of(e);
}
}
@SuppressWarnings("unchecked")
public static <T> T send(
@NonNull final Object object,
@NonNull final String method,
final Object... args) {
int arguments = args.length;
Class[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
try {
return (T)getMethod(object.getClass(), method, parameterTypes).invoke(object, args);
} catch (Exception e) {
throw SneakyException.of(e);
}
}
public static <T> T get(
@NonNull final Object object,
@NonNull final String property) {
return send(object, "get" + capitalize(property));
}
public static boolean is(
@NonNull final Object object,
@NonNull final String property) {
return send(object, "is" + capitalize(property));
}
public static void set(
@NonNull final Object object,
@NonNull final String property,
@NonNull final Object value
) {
send(object, "set" + capitalize(property), value);
}
private static String capitalize(String line)
{
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
@SuppressWarnings("unchecked")
public static <T> T set(
@NonNull final Object object,
@NonNull final String method,
final Object... args) {
int arguments = args.length;
Class[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
try {
return (T)getMethod(object.getClass(), method, parameterTypes).invoke(object, args);
} catch (Exception e) {
throw SneakyException.of(e);
}
}
private static Method getMethod(@NonNull Class<?> clazz, @NonNull String methodName, @NonNull Class<?>[] parameterTypes) throws NoSuchMethodException {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
// If the requested method is not public, try to make it public
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method;
} catch (NoSuchMethodException e) {
Class <?> superClazz = clazz.getSuperclass();
if (superClazz == null) {
throw new NoSuchMethodException(methodName + " not existent in the class chain");
}
return getMethod(superClazz, methodName, parameterTypes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.