This article creates an object of java.lang.Void,
This is an article that tried to call the method of the object.
However, creating an object of java.lang.Void probably has no merit, so it's just a play.
I also wrote a commentary in the comments.
import java.lang.reflect.Constructor;
public class CreateVoid {
public static void main(String... args) throws Exception {
//How to get Class by specifying the class name as a character string
Class<Void> voidClazz1 = (Class<Void>)Class.forName("java.lang.Void");
Void o1 = getVoid(voidClazz1);
//How to get the Class from the actual method
Class<Void> voidClazz2 = (Class<Void>)CreateVoid.class.getMethod("voidMethod", new Class[]{}).getReturnType();
Void o2 = getVoid(voidClazz2);
System.out.println(o1);//java.lang.Void@1c6b6478
//Since the equals method is not overridden, it will always be false if it is another instance.
System.out.println(o1.equals(o2));//false
System.out.println(o1.hashCode());//476800120
System.out.println(o1.toString());//java.lang.Void@1c6b6478
System.out.println(o1.getClass());//class java.lang.Void
}
//If it is void, it will be a primitive type, so Void(=java.lang.Void)is.
public Void voidMethod(){return null;};
//Class<Void>Create a Void object from
private static Void getVoid(Class<Void> voidClazz) throws Exception {
//Looking into the JDK source`private Void() {}`And the constructor is private so you need to do the following
//1.Write getDeclaredConstructor instead of getConstructor
//2.Set the accessible flag to true
Constructor<?> declaredConstructor = voidClazz.getDeclaredConstructor(new Class[]{});
declaredConstructor.setAccessible(true);
return (Void)declaredConstructor.newInstance(new Object[]{});
}
}
Recommended Posts