对于我的项目之一,我必须对构造函数进行动态调用。但是由于这是Java 7,而不是“经典”反射API,所以我使用java.lang.invoke。
码:
@ParametersAreNonnullByDefault
public class PathMatcherProvider
{
private static final MethodHandles.Lookup LOOKUP
= MethodHandles.publicLookup();
private static final MethodType CONSTRUCTOR_TYPE
= MethodType.methodType(void.class, String.class);
private final Map<String, Class<? extends PathMatcher>> classMap
= new HashMap<>();
private final Map<Class<? extends PathMatcher>, MethodHandle> handleMap
= new HashMap<>();
public PathMatcherProvider()
{
registerPathMatcher("glob", GlobPathMatcher.class);
registerPathMatcher("regex", RegexPathMatcher.class);
}
public final PathMatcher getPathMatcher(final String name, final String arg)
{
Objects.requireNonNull(name);
Objects.requireNonNull(arg);
final Class<? extends PathMatcher> c = classMap.get(name);
if (c == null)
throw new UnsupportedOperationException();
try {
return c.cast(handleMap.get(c).invoke(arg));
} catch (Throwable throwable) {
throw new RuntimeException("Unhandled exception", throwable);
}
}
protected final void registerPathMatcher(@Nonnull final String name,
@Nonnull final Class<? extends PathMatcher> matcherClass)
{
Objects.requireNonNull(name);
Objects.requireNonNull(matcherClass);
try {
classMap.put(name, matcherClass);
handleMap.put(matcherClass, findConstructor(matcherClass));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException("cannot find constructor", e);
}
}
private static <T extends PathMatcher> MethodHandle findConstructor(
final Class<T> matcherClass)
throws NoSuchMethodException, IllegalAccessException
{
Objects.requireNonNull(matcherClass);
return LOOKUP.findConstructor(matcherClass, CONSTRUCTOR_TYPE);
}
public static void main(final String... args)
{
new PathMatcherProvider().getPathMatcher("regex", "^a");
}
}
好,这有效。
我的问题是与此行:
return c.cast(handleMap.get(c).invoke(arg));
如果将
invoke
替换为invokeExact
,则会得到以下堆栈跟踪:Exception in thread "main" java.lang.RuntimeException: Unhandled exception
at com.github.fge.filesystem.path.matchers.PathMatcherProvider.getPathMatcher(PathMatcherProvider.java:62)
at com.github.fge.filesystem.path.matchers.PathMatcherProvider.main(PathMatcherProvider.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.invoke.WrongMethodTypeException: expected (String)RegexPathMatcher but found (String)Object
at java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:350)
at java.lang.invoke.Invokers.checkExactType(Invokers.java:361)
at com.github.fge.filesystem.path.matchers.PathMatcherProvider.getPathMatcher(PathMatcherProvider.java:60)
我不太明白。
GlobPathMatcher
和RegexPathMatcher
都使用一个以String
作为参数的构造函数,因此两者的MethodType
都是CONSTRUCTOR_TYPE
中定义的。如果不是的话,我无论如何都无法“捕获” MethodHandle
。但是我得到了
WrongMethodTypeException
。为什么?编辑:这是我阅读答案后的代码;现在我不需要中间映射:我只需要一张映射,将
String
映射到MethodHandle
:@ParametersAreNonnullByDefault
public class PathMatcherProvider
{
private static final MethodHandles.Lookup LOOKUP
= MethodHandles.publicLookup();
private static final MethodType CONSTRUCTOR_TYPE
= MethodType.methodType(void.class, String.class);
private final Map<String, MethodHandle> handleMap
= new HashMap<>();
public PathMatcherProvider()
{
registerPathMatcher("glob", GlobPathMatcher.class);
registerPathMatcher("regex", RegexPathMatcher.class);
}
public final PathMatcher getPathMatcher(final String name, final String arg)
{
Objects.requireNonNull(name);
Objects.requireNonNull(arg);
final MethodHandle handle = handleMap.get(name);
if (handle == null)
throw new UnsupportedOperationException();
try {
return (PathMatcher) handle.invokeExact(arg);
} catch (Throwable throwable) {
throw new RuntimeException("Unhandled exception", throwable);
}
}
protected final void registerPathMatcher(@Nonnull final String name,
@Nonnull final Class<? extends PathMatcher> matcherClass)
{
Objects.requireNonNull(name);
Objects.requireNonNull(matcherClass);
final MethodHandle handle;
final MethodType type;
try {
handle = LOOKUP.findConstructor(matcherClass, CONSTRUCTOR_TYPE);
type = handle.type().changeReturnType(PathMatcher.class);
handleMap.put(name, handle.asType(type));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException("cannot find constructor", e);
}
}
}
最佳答案
当编译器发出invokeExact调用时,它将Object记录为预期的返回类型。从MethodHandle javadoc(重点是我的):
在运行时,方法句柄实际上返回RegexPathMatcher,因此invokeExact失败,并出现WrongMethodTypeException。
您需要使用(编译时)强制转换显式指定返回类型:
return (RegexPathMatcher)handleMap.get(c).invokeExact(arg);
除了需要在不同的PathMatcher实现上通用之外,因此您应该将方法句柄转换为使用asType返回PathMatcher,然后使用PathMatcher作为预期的返回类型进行调用。//in findConstructor
MethodHandle h = LOOKUP.findConstructor(matcherClass, CONSTRUCTOR_TYPE);
return h.asType(h.type().changeReturnType(PathMatcher.class));
//in getPathMatcher
return (PathMatcher)handleMap.get(c).invokeExact(arg);