简体   繁体   中英

How to use invokedynamic to execute method with polymorphism?

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.

您可以使用Java反射,例如,使用ConstructorUtils.invokeConstructor(...)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM