4 Replies Latest reply: Sep 13, 2010 9:57 AM by 796386 RSS

    Generics for creation method

    796386
      Hi,
      I have a Factory class for creating various objects.
      The API is like this:
      public static <T extends BusinessEntity> T createEntity(Class<T> t)
      The usage is as:
      Car car = Factory.create(Car.class);
      Notice I have to specy the class type as a parameter.

      I note with things like the collections framework, I don't have to specify a class parameter. For example, I can just do

      List<Car> cars = new ArrayList<Car>();

      I was wondering is there anyway I can improve my Factory method, so I don't have to specify a .class parameter.

      Thanks a million.
        • 1. Re: Generics for creation method
          843793
          No, you can't really do that.

          The problem is that generics are implemented with a technique called generics. Basically (and quite over-simplified) the Java runtime doesn't know a lot about generics (it only knows the upper bound, which is often simply java.lang.Object). The compiler knows more than that, but the info is not used at runtime.

          That means that your createEntity() method can't actually do anything with the concrete type T, unless it also gets some runtime-visible information about it (in your case a correct Class<T> object).

          The reason why ArrayList (and other collections) don't need this kind of information is that it doesn't actually create any T objects. It just stores them (and it doesn't even check if the objects are actually T, it depends on compile-time checks for that).
          • 2. Re: Generics for creation method
            796085
            JoachimSauer wrote:
            The problem is that generics are implemented with a technique called generics.
            He meant "generics are implemented with a technique called *erasure*"
            • 3. Re: Generics for creation method
              843793
              dannyyates wrote:
              JoachimSauer wrote:
              The problem is that generics are implemented with a technique called generics.
              He meant "generics are implemented with a technique called *erasure*"
              Oops ... I sure did. I should really proof-read my posts.
              • 4. Re: Generics for creation method
                796386
                Good answers.