Edgar
Edgar

Reputation: 1120

JAVA java.lang.reflect.Constructor cannot call Date constructor

receiving "java.lang.reflect.invocationtargetexception" calling instance of date(String) constructor.

code:

Constructor constr = fieldType.getConstructor(String.class);
if (constr != null) {
    val = constr.newInstance(val.toString()); // here is exeption
}

 fieldType = java.util.Date;
 val.getclass() = java.sql.Date,
 val.toString() = 2014-05-19
 constr [is not null] = java.util.Date(java.lang.String);

Maybe someone can help me with solution, how to call constructor properly?

Upvotes: 2

Views: 633

Answers (1)

icza
icza

Reputation: 418137

The problem is that the constructor of Date throws an Exception because Date(String) expects the String parameter to be in a specific format and the String you pass to it is in a different format.

When using reflection if the constructor throws an exception, Constructor.newInstance() will wrap it and throw an InvocationTargetException which is what you get.

The required format for Date(String) is for example:

Sat, 12 Aug 1995 13:30:00 GMT

So you need to pass a date string in this format if you want Date(String) to work and not throw an Exception.

You can find more info on the required format in the javadoc of Date.parse() because the constructor calls this to parse the String parameter.

Upvotes: 5

Related Questions