Skip to content

Instantly share code, notes, and snippets.

@CalebWhiting
Created October 27, 2016 17:17
Show Gist options
  • Save CalebWhiting/0d222d1144bd4fc0ca48f3beb1830e3a to your computer and use it in GitHub Desktop.
Save CalebWhiting/0d222d1144bd4fc0ca48f3beb1830e3a to your computer and use it in GitHub Desktop.
package com.unicus.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jdk.internal.org.objectweb.asm.Type;
/**
* @author Caleb Whiting
*/
public class MethodReference {
private final String key;
private final String owner;
private final String name;
private final String signature;
private final int expectedParameters;
private final int opaquePredicate;
private Method value;
public MethodReference(String key, String owner, String name, String signature, int expectedParameters, int opaquePredicate) {
this.key = key;
this.owner = owner;
this.name = name;
this.signature = signature;
this.expectedParameters = expectedParameters;
this.opaquePredicate = opaquePredicate;
}
public String getKey() {
return key;
}
public String getOwner() {
return owner;
}
public String getName() {
return name;
}
public String getSignature() {
return signature;
}
public int getExpectedParameters() {
return expectedParameters;
}
public int getOpaquePredicate() {
return opaquePredicate;
}
public Object invoke(Object reference, Object... arguments) {
try {
if (arguments.length != getExpectedParameters()) {
Object[] args = new Object[getExpectedParameters()];
System.arraycopy(arguments, 0, args, 0, arguments.length);
args[args.length - 1] = getOpaquePredicate();
arguments = args;
}
return get().invoke(reference, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public Method get() {
if (value != null) {
return value;
}
Class owner = ReflectContext.get().loadClass(getOwner());
Type type = Type.getType(getSignature());
for (Method method : owner.getMethods()) {
if (method.getName().equals(getName()) && Type.getType(method).equals(type)) {
method.setAccessible(true);
return value = method;
}
}
throw new RuntimeException("Couldn't find method " + getOwner() + "." + getName() + " '" + getSignature() + "'");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment