Skip to content

Instantly share code, notes, and snippets.

@vietj
Created January 26, 2015 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vietj/a87ffcba5ab24d7da546 to your computer and use it in GitHub Desktop.
Save vietj/a87ffcba5ab24d7da546 to your computer and use it in GitHub Desktop.
public class ConvertingJavaMethod extends JavaMethod {
private final Class boxedReturnType;
private final JavaUtil.JavaConverter returnConverter;
public ConvertingJavaMethod(Ruby runtime, Method method) {
super(runtime, method);
method.setAccessible(true);
if (method.getReturnType().isPrimitive() && method.getReturnType() != void.class) {
this.boxedReturnType = CodegenUtils.getBoxType(method.getReturnType());
} else {
this.boxedReturnType = method.getReturnType();
}
returnConverter = JavaUtil.getJavaConverter(method.getReturnType());
}
@Override
public IRubyObject invoke(IRubyObject[] args) {
IRubyObject ret = super.invoke(args);
if (ret instanceof JavaObject) {
ret = convertReturn(((JavaObject) ret).getValue());
}
return ret;
}
private IRubyObject convertReturn(Object result) {
if (result != null && result.getClass() != boxedReturnType) {
// actual type does not exactly match method return type, re-get converter
// FIXME: when the only autoconversions are primitives, this won't be needed
return JavaUtil.convertJavaToUsableRubyObject(getRuntime(), result);
}
return JavaUtil.convertJavaToUsableRubyObjectWithConverter(getRuntime(), result, returnConverter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment