Reputation: 121
In a dynamic language for Java where all variables are declared as java.lang.Object
, I need to call Java built-in classes. For example, java.math.BigDecimal
constructor can accept number, String and etc.
a = 10 // a is `java.lang.Object`
create java.math.BigDecimal(a) // should call constructor that accept number
a = '1.234' // a is `java.lang.Object`
create java.math.BigDecimal(a) // should call constructor that accept String
Are there java.lang.invoke
that I can use to generate appropriate MethodHandle
? The MethodHandle
should accept an java.lang.Object
as its argument, but when invoked, it should call the proper constructor.
Upvotes: 0
Views: 447
Reputation: 13663
You're looking to create an inline cache. Initially, your bootstrap method will return a call site bound to a method handle that inspects its argument type, locates the proper constructor on BigInteger (or whatever type -- pass this type as a static argument to the bootstrap method), and re-links the call site to first check for this type and call the right constructor, or fall back to looking up the constructor again. Thus if that call site only passes Strings, you only perform the reflective search for a constructor once, and further calls are just a type check and direct call to the constructor. (This is very similar to what the JVM does to inline virtual method calls.)
I don't know invokedynamic well enough to give you example code for this, but I can point you to the JSR 252 Cookbook doing something similar, which is documented with a talk from the JVM Language Summit 2011 and accompanying slides.
Upvotes: 0
Reputation: 11579
You can use java reflection, for example using ConstructorUtils.invokeConstructor(...)
Upvotes: 1