Created
March 10, 2019 11:55
-
-
Save micycle1/a579dd16adecc805ce0a0c3d64d3c426 to your computer and use it in GitHub Desktop.
Reflecting Java instance methods with primitives
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final Map<Class<?>, Class<?>> W2P; // wrapper to primitive | |
static { | |
W2P = new HashMap<>(); | |
W2P.put(Boolean.class, boolean.class); | |
W2P.put(Byte.class, byte.class); | |
W2P.put(Character.class, char.class); | |
W2P.put(Double.class, double.class); | |
W2P.put(Float.class, float.class); | |
W2P.put(Integer.class, int.class); | |
W2P.put(Long.class, long.class); | |
W2P.put(Short.class, short.class); | |
W2P.put(Void.class, void.class); | |
} | |
Object invokeMethod(String name, Object... args) { // invoke on this object | |
Class<? extends Object>[] classes = new Class<?>[args.length]; | |
for (int i = 0; i < args.length; i++) { | |
if (W2P.containsKey(args[i].getClass())) { | |
classes[i] = W2P.get(args[i].getClass()); | |
} else { | |
classes[i] = args[i].getClass(); | |
} | |
} | |
try { | |
Method method = this.getClass().getSuperclass().getDeclaredMethod(name, classes); | |
Object ret = method.invoke(this, args); | |
return ret; | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e) { | |
System.err.println(e); | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment