Java: How to set a default for “T” in SomeClass?

后端 未结 4 1667
走了就别回头了
走了就别回头了 2020-12-11 14:35

Is there a way to specify a default type for a generic template?

Let\'s say I have a Monkey class. Monkeys can live in different Environment

相关标签:
4条回答
  • 2020-12-11 15:08

    Why not just use the base class of the Generic? Monkey<Environment> ?

    0 讨论(0)
  • 2020-12-11 15:12

    Jen, your question doesn't put any context around why you want to use a generics. It would really be helpful if you stated what it is you are trying to do and why you are using generics. Generics exist IMHO mainly to avoid having to do class casts everywhere when putting things into and taking them out of collections that are designed to be generic holders of types. This kinda implies iteration over a bunch of things, but not necessarily.

    My point is, I didn't see any part of your class or code that required being able to create a custom version of the monkey class that required iterating over environments. If this is not the case, you probably don't even need generics. Instead, you probably want dependency injection. The monkey class should have a constructor that takes an environment. Environment is an interface (or simple base class). The interface has several default operations like getBathroomLocation() and getFoodLocation(). Instead of using generics to create a type of monkey that lives in the zoo, you create a monkey and inject the dependency of which environment it lives in.

    Monkey monkey = new Monkey(new CostaRicaJungle());
    

    Later on, you can set this environment to something different. The wild monkey gets captured, and you now do

    monkey.setEnvironment(new BronxZoo());
    

    Later, the monkey gets an living condition change, and you do a

    monkey.setEnvironment(new SanDiegoZoo());
    
    0 讨论(0)
  • 2020-12-11 15:15

    No you can't: http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B

    Generic type parameters cannot have default arguments.

    What about making something like this:

    public class Monkey extends Monkey<YourType>
    

    Obviusly you'll "waste" the ability to inherit.

    EDIT 1: Another interesting thing is do the reverse of what I suggested,

    public class Monkey<T> extends Monkey
    

    In this case all generics class Monkey inherits Monkey, in some cases, this is a very interesting thing (expecially when you notice that some instance-methods fits in all classes without requiring the generic). This approach is used in Castle ActiveRecord (I've seen it used in C#, not in Java), and I find it beautiful.

    0 讨论(0)
  • 2020-12-11 15:20

    No, you can't do that. Generic parameters don't have default values. You could re-organize your type hierarchy so that there's a GenericMonkey and a DefaultMonkey that sets the generic parameter to your desired default.

    0 讨论(0)
提交回复
热议问题