Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

java - Is Void really uninstantiable?

The javadoc for Void says:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

but the constructor is simply:

private Void() {}

and this code instantiates a Void:

Constructor<Void> c = Void.class.getDeclaredConstructor();
c.setAccessible(true);
Void v = c.newInstance(); // Hello sailor

So Void is not uninstantiable.

Would there have been a way to make Void truly uninstantiable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rohit is quite right that throwing an exception is "good enough" for most use cases. However, it looks like it might be possible to bypass even that, using sun.misc.Unsafe:

public native Object allocateInstance(Class cls) throws InstantiationException

Allocate an instance but do not run any constructor. Initializes the class if it has not yet been.

(Note that I haven't actually tested that this works)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...