Why does Boolean.class.newInstance() throw exception?
I think the sunject's pretty self-explanatory. I use JDK 1.6.0 update 26, and created a new project开发者_运维知识库 with just one line to confirm this:
Boolean.class.newInstance();
and it throws the following:
Exception in thread "main" java.lang.InstantiationException: java.lang.Boolean
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
Does it suppose to fail? If so, why?
The Boolean
class has two constructors, both take one argument. Calling Boolean.class.newInstance()
is trying to call a zero-arg constructor that doesn't exist.
Given a class you can find out what it needs to be constructed:
Class cl = // initialize somehow
// get all constructors for class
Constructor[] constructors = cl.getConstructors();
// for each constructor
for(Constructor c : constructors)
{
// if there is a zero-parameter constructor
if(c.getParameterTypes().length == 0)
{
// then we can safely create a constructor for it
cl.newInstance();
}
}
The Boolean
class has two different constructors. Both of them take one argument. One of them takes a boolean
itself but the other takes a String
. If the string is NOT empty when you pass it to the Boolean
class, it will be recognized as setting the Boolean
to true
. If it is null or contains nothing, then it is false
.
精彩评论