3
I have a generic class called Quantity<UnitType>
, and in some methods of another class, I need to get an object of that class in a specific type. See the code below:
interface UnitType {}
enum Distance implements UnitType {
FEET, METERS
}
enum Weight implements UnitType {
POUNDS, KILOGRAMS
}
class Quantity<T extends UnitType> {
public Quantity(float value, T unit) {
// ...
}
}
public class Test {
public static void main(String[] args) {
Test.func(new Quantity<Weight>(30, Weight.KILOGRAMS));
}
public static void func(Quantity<Weight> value) {
// ...
}
}
The above code compiles as expected. The problem is that if I do not specify the type on startup and pass as argument an attribute of Distance
, the code will also compile.
// Compila. Isso é um problema, pois o método só aceita "Weight"
Test.func(new Quantity(30, Distance.FEET));
// Não compila. É isso o que eu quero.
Test.func(new Quantity<Distance>(30, Distance.FEET));
What can I do to force the user to pass a type to the generic class, or else, "filter" objects that are just from Weight
?
I think this is a misconception, but still adopting think it has nothing to do. I don’t know Java deeply, but I’m guessing it’s not possible. I fear it may be a Java problem, I may be mistaken, but if I am the creator of language I would do the opposite, that is, I would only accept explicitly since there may be ambiguity, inference only when there is not. Of course there’s always a solution, but not the way you’re doing it. I don’t answer because I’m not sure either how much I can do differently in the problem. But I was curious about Java.
– Maniero
@Maniero Unless I have interpreted the question very wrong, yes to do what he wants and it is something that is relatively simple and easy.
– Victor Stafusa
@Victorstafusa didn’t work: https://ideone.com/mwcteh. It was the first thing I did, actually I used
Weight
becauseUnitType
is just what he doesn’t want, he wantsWeight
only. But both compiler accepts and inferred.– Maniero
@Piovezan the question is just that.
– Maniero
@Maniero I edited the answer below.
– Victor Stafusa
@Victorstafusa is a solution, not that it does what he did, complicates a little, and it seems to me that by language failure. As I said, there is no way in the form he wants. Later I will do some more tests.
– Maniero
I think this question is good and useful to the community, something that has been rare in recent times. Whoever voted negative could explain why?
– Victor Stafusa
Related issue that can help better understand the problem of raw types in Java: https://answall.com/q/229885/157404
– JeanExtreme002