Per uno dei miei progetti devo fare invocazioni dinamiche del costruttore. Ma dal momento che si tratta di Java 7, anziché dell'API di riflessione "classico", utilizzo java.lang.invoke.Perché non posso I .invokeExact() qui, anche se MethodType è OK?
Codice:
@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");
}
}
OK, questo funziona.
Il problema che ho è con questa linea:
return c.cast(handleMap.get(c).invoke(arg));
Se sostituisco invoke
con invokeExact
, ottengo questo stack trace:
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)
non ho ben capito. Entrambi GlobPathMatcher
e RegexPathMatcher
utilizzano un singolo costruttore con un String
come argomento e lo MethodType
per entrambi è quindi definito in CONSTRUCTOR_TYPE
. In caso contrario, non avrei potuto "afferrare" lo MethodHandle
s.
Eppure ho un WrongMethodTypeException
. Perché?
MODIFICA: ecco il codice dopo aver letto la risposta; ora non ho bisogno la mappa intermedio: ho solo avere una mappa, la mappatura di un String
ad un 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);
}
}
}
quindi il tipo di argomento 'c.cast()' viene registrato come previsto? Hmm ho completamente sovrascritto questa parte, spiegazione meravigliosa;) – Vogel612
@ Vogel612: No, se non c'è cast sull'espressione di chiamata del metodo, il tipo di reso previsto è Object anche se l'espressione viene utilizzata dove è richiesto un tipo più specifico. Le invocazioni polimorfiche di firma non sono espressioni poligonali (ad esempio lambdas) in cui il tipo viene dedotto in contesti di invocazione. –
OK, ho bisogno di rileggere la tua risposta di nuovo in profondità, ma le modifiche al codice che hai suggerito funzionano ... Lo accetterò dopo un'altra lettura;) – fge