Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #35379

Re: Generics

From Marcel Mueller <news.5.maazl@spamgourmet.org>
Newsgroups comp.lang.java.programmer
Subject Re: Generics
Date 2016-08-17 21:20 +0200
Organization MB-NET.NET for Open-News-Network e.V.
Message-ID <np2dd0$mtg$1@gwaiyur.mb-net.net> (permalink)
References <681a67de-8a78-46ab-a028-5176a48df402@googlegroups.com>

Show all headers | View raw


On 17.08.16 20.59, Eric Douglas wrote:
> Say we have 3 classes.
>
> public class TestA<E extends TestB> {
> }
>
> public abstract class TestB {
> }
>
> public class TestC extends TestB {
> }
>
> Now we create an instance.
>
> TestA<TestC> testMe = new TestA();
>
> Now within class TestA how do we tell it instance testMe is referencing TestC?

Not at all.

Java uses the type erasure pattern to implement generics. This means 
that any instance of TestA will never know to what type it relies to. 
Basically generics in Java are only compile time checks for type 
integrity and automatically generated down casts in the compiled code.
In fact you can even cast from TestA<TestB> to TestA<TestC> and with 
some warnings also to TestA which is equvalent to TestA<object>. And 
like any other downcast the are valid as long as the TestA instance is 
only used with TestC instances so far.

This is different e.g. from .NET where you can access the type 
information at compile time and run time per reflection. And it is even 
more different from C++ templates where even the implementation for each 
type might be entirely distinct.

> The only thing I could find is to add a method or constructor which passes in a reference to TestC.class or the class name,

Yes, that's an option.

But the more interesting question is: why do you need to know the type 
of TestC within of TestA? It won't help you much without reflection.

You should also keep in mind that even if the type definition says 
TestA<TestC> your TestA instance might be used to handle object of type 
TestD which inherits from TestC. So the compile time type and the 
runtime type are not the same unless TestC is final.


Marcel

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Generics Eric Douglas <e.d.programmer@gmail.com> - 2016-08-17 11:59 -0700
  Re: Generics Marcel Mueller <news.5.maazl@spamgourmet.org> - 2016-08-17 21:20 +0200
  Re: Generics Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-08-17 15:22 -0400
    Re: Generics Eric Douglas <e.d.programmer@gmail.com> - 2016-08-17 14:03 -0700
      Re: Generics Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-08-17 20:06 -0400
      Re: Generics Robert Klemme <shortcutter@googlemail.com> - 2016-08-18 08:23 +0200
        Re: Generics Eric Douglas <e.d.programmer@gmail.com> - 2016-08-18 05:34 -0700

csiph-web