Skip to content

Instantly share code, notes, and snippets.

@vemacs
Created May 26, 2015 23:11
Show Gist options
  • Select an option

  • Save vemacs/faa7bd7d6fa7749f4588 to your computer and use it in GitHub Desktop.

Select an option

Save vemacs/faa7bd7d6fa7749f4588 to your computer and use it in GitHub Desktop.
import com.google.common.base.Preconditions;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionHelpers {
private static Table<Class<?>, String, Method> cachedNoArgsMethods = HashBasedTable.create();
private static Table<Class<?>, MethodArgs, Method> cachedArgsMethods = HashBasedTable.create();
private static Table<Class<?>, String, Field> cachedFields = HashBasedTable.create();
public static Method getCachedMethod(Class<?> clazz, String name) throws NoSuchMethodException {
Preconditions.checkNotNull(clazz, "clazz");
Preconditions.checkNotNull(name, "name");
if (cachedNoArgsMethods.contains(clazz, name))
return cachedNoArgsMethods.get(clazz, name);
Method method = clazz.getMethod(name);
method.setAccessible(true);
cachedNoArgsMethods.put(clazz, name, method);
return method;
}
public static Method getCachedMethod(Class<?> clazz, String name, Class<?>... args) throws NoSuchMethodException {
Preconditions.checkNotNull(clazz, "clazz");
Preconditions.checkNotNull(name, "name");
MethodArgs args1 = new MethodArgs(name, args);
if (cachedArgsMethods.contains(clazz, args1))
return cachedArgsMethods.get(clazz, args1);
Method method = clazz.getMethod(name, args);
method.setAccessible(true);
cachedArgsMethods.put(clazz, args1, method);
return method;
}
public static Field getCachedField(Class<?> clazz, String name) throws NoSuchFieldException {
Preconditions.checkNotNull(clazz, "clazz");
Preconditions.checkNotNull(name, "name");
if (cachedFields.contains(clazz, name))
return cachedFields.get(clazz, name);
Field field = clazz.getField(name);
field.setAccessible(true);
cachedFields.put(clazz, name, field);
return field;
}
@AllArgsConstructor
@EqualsAndHashCode
private static class MethodArgs {
private final String name;
private final Class<?>[] args;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment