That is not how it works. You can, however, use polymorphism, to achieve a useful result.
Solution with polymorphism
Base generic (and abstract) property
public abstract class Property<T> {
T value;
public abstract void setValue(String input);
}
Property for Strings
public class StringProperty extends Property<String> {
@Override
public void setValue(String input) {
this.value = input;
}
}
Property for integers
public class IntegerProperty extends Property<Integer> {
@Override
public void setValue(String input) {
this.value = Integer.valueOf(input);
}
}
Not sure what your actual goal is, but this approach might work.
Note, that input instanceof T
will fail, because of type erasure. It's not gonna work.
Solution with Class<T>
as argument
To elaborate more on your approach, this would work - but it's UGLY.
Ugly and not very convenient. No idea why you'd want it, tbh.
class Property<T> {
public T value;
private final Class<T> clazz;
public Property(Class<T> clazz) {
super();
this.clazz = clazz;
}
@SuppressWarnings("unchecked")
public void setValue(String input) {
if (clazz.isAssignableFrom(String.class)) {
value = (T) input;
} else if (clazz.isAssignableFrom(Integer.class)) {
value = (T) Integer.valueOf(input);
} else if (clazz.isAssignableFrom(Boolean.class)) {
value = (T) Boolean.valueOf(input);
} else if (clazz.isAssignableFrom(Double.class)) {
value = (T) Double.valueOf(input);
} else {
throw new IllegalArgumentException("Bad type.");
}
}
}
Used like so:
Property<String> ff = new Property<>(String.class);
ff.setValue("sdgf");
Property<Integer> sdg = new Property<>(Integer.class);
sdg.setValue("123");
System.out.println(ff.value);
System.out.println(sdg.value);
Solution with Reflection
Apparently, it's possible to figure out the parameter used to instantiate property.
This little magic formula gives you just that:
(Class<?>) getClass().getTypeParameters()[0].getBounds()[0]
I don't even know how I managed to find it. Well, here we go:
class Property<T> {
T value;
@SuppressWarnings("unchecked")
public void setValue(String input)
{
// BEHOLD, MAGIC!
Class<?> clazz = (Class<?>) getClass().getTypeParameters()[0].getBounds()[0];
if (clazz.isAssignableFrom(String.class)) {
value = (T) input;
} else if (clazz.isAssignableFrom(Integer.class)) {
value = (T) Integer.valueOf(input);
} else if (clazz.isAssignableFrom(Boolean.class)) {
value = (T) Boolean.valueOf(input);
} else if (clazz.isAssignableFrom(Double.class)) {
value = (T) Double.valueOf(input);
} else {
throw new IllegalArgumentException("Bad type.");
}
}
}
And don't look at me, I wouldn't use that. I have some common sense.
String
if the argument is of type string. – Metamorphosis