Created
August 27, 2020 08:13
-
-
Save bric3/4f45905c1423280d401f3e89c93cd010 to your computer and use it in GitHub Desktop.
Uses MethodHandle to access private package
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
public abstract class PrivateConstructors { | |
// public class CustomIterable<V> implements Iterable<V> { | |
// CustomIterable() {} | |
// } | |
@SuppressWarnings("unchecked") | |
private static <I extends T, T> I newInstanceOf(Class<T> clazz) throws Throwable { | |
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(clazz, MethodHandles.lookup()); | |
MethodHandle methodHandle = lookup.findConstructor(clazz, MethodType.methodType(void.class)); | |
Supplier<T> constructor = (Supplier<T>) LambdaMetafactory.metafactory( | |
lookup, | |
"get", | |
MethodType.methodType(Supplier.class), | |
methodHandle.type().generic(), | |
methodHandle, | |
methodHandle.type() | |
).getTarget().invokeExact(); | |
return (I) constructor.get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment