Skip to content

Instantly share code, notes, and snippets.

@bric3
Created August 27, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bric3/4f45905c1423280d401f3e89c93cd010 to your computer and use it in GitHub Desktop.
Save bric3/4f45905c1423280d401f3e89c93cd010 to your computer and use it in GitHub Desktop.
Uses MethodHandle to access private package
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