I have the following class:
public final class Param<T>
{
private final String name;
private T value;
public Param(String name)
{
this.name = name;
}
public void setValue(T value) { this.value = value;}
public T getValue() { return value; }
}
I would instantiate it in the following way:
Param<Long> foo = new Param<>("bar");
Param<String> baz = new Param<>("foo");
I want to add a public boolean validate(String value)
method to this class, which would do something like the following:
public boolean validate(String value)
{
try
{
if (this.value instanceof String)
return true;
if (this.value instanceof Long)
this.value = (T) Long.valueOf(value);
else if (this.value instanceof Integer)
this.value = (T) Integer.valueOf(value);
//Snip.. a few more such conditions for Double, Float, and Booleans
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
My question is, will the above method work, for correctly determining the 'type' of T
and for correctly casting string value
to T value
? Or should I use a different approach for validating the parameters?