Generics------type parameter

Hi,
I have a question about following code.
public class A<T1 extends Thread> {
public class B<T1 extends Thread> extends A<T1> {
public class D<T4<T1 extends Thread> extends A<T1>> {
}My question: Why class D can't compile?
And how can I get the T1 in D?
I need T1 in class D

Thank you very much.
Maybe I shouldn't write the class B above
The class B and Thread are only examples.
Nothing relatee them.
I rewrite the code example:
public interface SomeInterface {
public class A<T extends SomeInterface> {
public class B <T2<T extends SomeInterface> extends A<T>>{
}OR:
public class B <T2<T> extends A<T extends SomeInterface>>{
B can't compile.
B has a type parameter T2 extended from A
How to define B?
I want use the the type parameter T of A in B.

Similar Messages

  • A question about a method with generic bounded type parameter

    Hello everybody,
    Sorry, if I ask a question which seems basic, but
    I'm new to generic types. My problem is about a method
    with a bounded type parameter. Consider the following
    situation:
    abstract class A{     }
    class B extends A{     }
    abstract class C
         public abstract <T extends A>  T  someMethod();
    public class Test extends C
         public <T extends A>  T  someMethod()
              return new B();
    }What I want to do inside the method someMethod in the class Test, is to
    return an instance of the class B.
    Normally, I'm supposed to be able to do that, because an instance of
    B is also an instance of A (because B extends A).
    However I cannot compile this program, and here is the error message:
    Test.java:16: incompatible types
    found   : B
    required: T
                    return new B();
                           ^
    1 errorany idea?
    many thanks,

    Hello again,
    First of all, thank you very much for all the answers. After I posted the comment, I worked on the program
    and I understood that in fact, as spoon_ says the only returned value can be null.
    I'm agree that I asked you a very strange (and a bit stupid) question. Actually, during recent months,
    I have been working with cryptography API Core in Java. I understood that there are classes and
    interfaces for defining keys and key factories specification, such as KeySpec (interface) and
    KeyFactorySpi (abstract class). I wanted to have some experience with these classes in order to
    understand them better. So I created a class implementing the interface KeySpec, following by a
    corresponding Key subclass (with some XOR algorithm that I defined myself) and everything was
    compiled (JDK 1.6) and worked perfectly. Except that, when I wanted to implement a factory spi
    for my classes, I saw for the first time this strange method header:
    protected abstract <T extends KeySpec> T engineGetKeySpec
    (Key key, Class<T> keySpec) throws InvalidKeySpecExceptionThat's why yesterday, I gave you a similar example with the classes A, B, ...
    in order to not to open a complicated security discussion but just to explain the ambiguous
    part for me, that is, the use of T generic parameter.
    The abstract class KeyFactorySpi was defined by Sun Microsystem, in order to give to security
    providers, the possibility to implement cryptography services and algorithms according to a given
    RFC (or whatever technical document). The methods in this class are invoked inside the
    KeyFactory class (If you have installed the JDK sources provided by Sun, You can
    verify this, by looking the source code of the KeyFactory class.) So here the T parameter is a
    key specification, that is, a class that implements the interface KeySpec and this class is often
    defined by the provider and not Sun.
    stefan.schulz wrote:
    >
    If you define the method to return some bound T that extends A, you cannot
    return a B, because T would be declared externally at invocation time.
    The definition of T as is does not make sense at all.>
    He is absolutely right about that, but the problem is, as I said, here we are
    talking about the implementation and not the invocation. The implementation is done
    by the provider whereas the invocation is done by Sun in the class KeyFactory.
    So there are completely separated.
    Therefore I wonder, how a provider can finally impelment this method??
    Besides, dannyyates wrote
    >
    Find whoever wrote the signature and shoot them. Then rewrite their code.
    Actually, before you shoot them, ask them what they were trying to achieve that
    is different from my first suggestion!
    >
    As I said, I didn't choose this method header and I'm completely agree
    with your suggestion, the following method header will do the job very well
    protected abstract KeySpec engineGetKeySpec (Key key, KeySpec key_spec)
    throws InvalidKeySpecException and personally I don't see any interest in using a generic bounded parameter T
    in this method header definition.
    Once agin, thanks a lot for the answers.

  • Nested-Generic Type with the same parameter as enclosing type?

    Greetings. I want to write a nested generic type with the same type parameter as the enclosing type. For example, consider:
    public interface BinaryTree<Type> {
         Node<Type> getRoot();
         interface Node<Type> {
              Type getValue();
              void setValue(Type value);
              Node<Type> getLeft();
              void setLeft(Node<Type> node);
              Node<Type> getRight();
              void setRight(Node<Type> node);
    }In this example, I want Node to be specified to the same type as the binary tree's parameter specification. Does anyone know how to do that? I have tried several methods and am at a loss.
    TIA

    Is there any way to declare that? Essentially I want
    the nested type to parameterize the enclosing type.I understand that but I don't think it's possible because of how java generics works.
    This ,
    SomeClass< SomeNestedClass<Type> >is wrong because you're supposed to give a formal type parameter within <> not an already defined type (like SomeNestedClass).
    If you instead do
    public class SomeClass<Type > {
        public static class SomeNestedClass<Type> {
    }To think of the two Type as the same formal type parameter is semantically incorrect. Both the outer type and the inner type must be able to participate in variable declarations "on their own". Say you do
    SomeClass<Integer> sc;Just because you did the above in which context is now SomeNestedClass supposed to be bound as SomeNestedClass<Integer>? To me this shows that SomeClass and SomeNestedClass cannot share the same formal type parameter.

  • Clear definition+examples- type variable, type parameter and type argument

    I am trying to fully understand the terms like type variable, type parameter and type argument as they apply to generics. Can anyone please give the exact definition and example of each of these terms. Also how these terms relate to the classes/interfaces in language model APIs of Java 6.

    http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

  • Retrieving dynamic information from generic type

    Hi,
    I am aware that the dynamic information can be asked for via Object's getClass(). For instance,
    List<? extends Number> list = new ArrayList<Integer>;
    System.out.println(list.getClass());
    This would return `ArrayList' as an "actual" or "static" type for `list' object. I was wondering whether there is a way to retrieve dynamic type information from the Field object. For example, if we have the following class:
    public class MyClass [
    public List<? extends Number> someList = new ArrayList<Long>;
    and retrieve its instance field:
    Field field = MyClass.class.getField("someList");
    Is it possible to ask for its dynamic type, which is ArrayList after erasure, just as I mentioned in my first example?
    Thank you

    Thank you Stefan, that does the trick. Initially, I had read the API incorrectly as to what argument get() takes. Now my problem is, how do I replace the type parameter of a generic class with a type argument that I only know at the runtime having only an object of Class<?> c. That is to say,
    class MyClass<T> {
      public T someClass;
      public MyClass(T t) {
        this.someClass = t;
      public T getT() { return this.someClass; }
      public static void myMethod(Class<?> c) {
        MyClass<c> mc = new MyClass<c>(c.newInstance());
      private void someOtherMethod() { // access getT() }
    }I know `new MyClass<c>()' is illegal, but is there a way I can create an instance of MyClass having only Class<?> c? Or is this even possible? If not, what are the work arounds?
    Thank you

  • Problem using self-referencing type parameter

    I seem to be having trouble using a self-referencing type parameter (or what's the name for it ;)
    Please consider this code:
    class Test<T extends Test<T>> implements ITest<T> {
         public T foo() {
              // does not work?!
              //return this;
              @SuppressWarnings("unchecked")
              T result = (T) this;
              return result;
    interface ITest<T extends ITest<T>> {
         T foo();
    }I need ITest.foo() to return T so that it would return the correct type when used in subinterfaces. I can see that Test.foo() must return T, so that is why I declared "T extends Test<T>".
    Trouble is, why does "this", which also implements ITest<T>, not satisfy the requirement of returning T?

    This is a common question. The problem is a flawed assumption about the declaration of ITest.
    The assumption is that:
    interface ITest<T extends ITest<T>>means that any implementation of ITest must be parameterized by itself. This is not the case.
    Consider the following
    public class Test<T extends Test<T>> implements ITest<T> {
        public static void main(String[] args){
            Bar b = new Foo().foo();
        public T foo() {
            @SuppressWarnings("unchecked")
            T result = (T) this;
            return result;
    class Foo extends Test<Bar> {
    class Bar extends Test<Bar>{
    interface ITest<T extends ITest<T>> {
    }Compiles and then fails with a classcastexception.
    Look again at ITest. The generic declaration requires that implementations are parameterized by self-parameterized instances of Test. That's different than saying the implementation itself is self-parameterized. The distinction is subtle but in the end you cannot declare classes that force sublcasses to be self-parameterized.
    You can, however, declare methods that force their arguments to be self-parameterized.

  • Retrieving generic type and letter

    Hi,
    I have a generic class -
    public class AAA <T extends BBB>implements Serializable From which I want to get its generic type (the easy part),
    and the generic type letter representation (In this case - T).
    Can I do this by reflection? If so how,
    Otherwise - is there any way I can do that which doesn't involve parsing the class as text?
    Thanks,
    Sharon.

    Class.getGenericDeclaration() should lead you to the letter T.
    The actual runtime type cannot be obtained because of erasure.
    If the class is under your control, you can play a trick:
    add to the constructor(s) a Class parameter and pass the actual type
    used.

  • Generic Type Declaration

    Hi in the below mentioned code while making the object of GenericsTypeTest, if we give the type parameter as Animal it works fine,where as if we give the parameter as Dog it gives the error,mentioned below. Can some one please explain why is this so?
    package generics;
    public class GenericsTypeTest<T extends Animal> { // use "T" instead
    //     of "?"
         T animal ;
         public static void main(String[] args) {
              GenericsTypeTest<Dog> dg= new GenericsTypeTest<Dog>(); 
              dg.animal.anotherMethod();
    class Animal{
         public static void anotherMethod(){
              System.out.println("hi iam an animal");
    class Dog extends Animal{
         public static void anotherMethod(){
              System.out.println("hi iam a dog");
    }Exception in thread "main" java.lang.NoSuchFieldError: animal
         at generics.GenericsTypeTest.main(GenericsTypeTest.java:8)

    Try remove static from anotherMethod() declaration. This error appeared because you wrote following in the row 8:
    dg.animal.anotherMethod();this is not static call.
    I changed you class and now it works:
    public class GenericsTypeTest<T extends Animal> {
         T animal ;
         public GenericsTypeTest(T animal){
              this.animal = animal;
         public static void main(String[] args) {
              GenericsTypeTest<Dog> dg= new GenericsTypeTest<Dog>(new Dog()); 
              dg.animal.anotherMethod();          
    class Animal{
         public void anotherMethod(){
              System.out.println("hi iam an animal");
    class Dog extends Animal{
         public void anotherMethod(){
              System.out.println("hi iam a dog");
    }

  • Defining enum with abstract method which returns a generic type

    Is it possible to define an abstract method which returns an geneic type like below? Thanks
    public enum Type{
         A{
              public List<Integer> getData(){}
         B{
              public Set<String> getData{}
         abstract<T> T getData();
    }

    vulee wrote:
    Why not?
    List<Integer> lst = Type.A.getData();Wonder, which compiler you use. Can't be Java6:
    # javac Enums.java
    Enums.java:23: incompatible types
    found   : java.util.Collection<capture#376 of ?>
    required: java.util.List<java.lang.Integer>
                    List<Integer> data = Type.A.getData();
                                                       ^
    1 errorEdit: Unless you do it the generic way as you proposed, which actually is a phoney. Because of the T being a generic method parameter, the compiler will infer it from the type of the variable it gets assigned to. Hence, both of the following will compile:
    List<Integer> lst = Type.A.getData();
    Set<String> lst2 = Type.A.getData(); // Runtime exceptionActually, javac is telling you that giving warnings on the enum constants redefined method return types.
    Edited by: stefan.schulz on Sep 10, 2008 11:38 PM

  • Type parameter instances.

    Hi, thanks for reading.
    I'm trying to implement a parametrized class which has an (obviously) parametrized array.
    The code:
    public class PQ<T> {
        protected T[] pq;
        protected Comparator<T> comparator;
        protected int N;That's OK but I can't create instances of pq.
    The error "Type parameter 'T' cannot be instantatied directly".
    What can I do? I need to work with that array instance to add, remove items, etc!
    Edited by: Akcents on Sep 29, 2008 7:04 PM

    Ugly? Yeah, arrays and generics don't go very nicely together. Here's my take at it (removed confusing N arg from constructor):
    public class AbstractPQ<T> {
        private Comparator<T> comparator;
        protected T[] pq;
        protected int N;
        protected AbstractPQ(Comparator<T> comparator) {
            pq = (T[]) new Object[0];
            this.comparator = comparator;
        }getMax now doesn't need casts anymore.
    If you don't like the warning generated for the unchecked cast to T[] in the constructor, refactor array creation into a method (or variable declaration) and use a SuppressWarnings-annotation:
    public class AbstractPQ<T> {
        private Comparator<T> comparator;
        protected T[] pq;
        protected int N;
        protected AbstractPQ(Comparator<T> comparator) {
            pq = createArray(0);
            this.comparator = comparator;
        @SuppressWarnings("unchecked")
        private T[] createArray(int length) {
           return (T[]) new Object[length];
        }Edited by: nygaard on Sep 29, 2008 10:05 PM

  • Reference to generic type Set E should be parmeterized

    I have the following code in a class:
    1:Event theEvent = (Event) session.load(Event.class, eventId);
                2:Set<Event> eventSet;
                3:eventSet = user.getFavouriteEvents();
                4:eventSet.add(theEvent);At line 3, I get the following warning message:
    Type safety: The expresson of raw type Set is converted to Set<Event>. References to generic type Set<E> should be parameterized.
    What does this mean? What do I need to do to get past this warning.
    Thanks
    Sharma

    Found the problem. I forgot to parameterize the Set in the getFavouriteEvents() method.
    Thanks
    Sharma

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • Import from database an internal table with generic Type : Web Dynpro ABAP

    Hi everyone,
    i have a requirement in which i'm asked to transfer data flow between two frameworks, from WD Component to another. The problem is that i have to transfer internal tables with generic types. i used the import/ export from database approache but in that way i get an error message saying "Object references and data references not yet supported".
    Here is my code to extract a generic internal table from memory.
        DATA l_table_f4 TYPE TABLE OF REF TO data.
      FIELD-SYMBOLS: <l_table_f4> TYPE STANDARD TABLE.
      DATA lo_componentcontroller TYPE REF TO ig_componentcontroller .
      DATA: ls_indx TYPE indx.
      lo_componentcontroller =   wd_this->get_componentcontroller_ctr( ).
      lo_componentcontroller->fire_vh_search_action_evt( ).
      ASSIGN l_table_f4 TO <l_table_f4>.
    *-- Import table for Help F4
      IMPORT l_table_f4 TO <l_table_f4> FROM DATABASE indx(v1) TO ls_indx ID 'table_help_f4_ID'.
    The error message is desplayed when last instruction is executed " IMPORT l_table_f4...".
    I saw another post facing the same problem but never solved "Generic Type for import Database".
    Please can anyone help ?
    Thanks & Kind regards.

    hi KIan,
    go:
    general type
    TYPE : BEGIN OF ty_itab,
               field1 TYPE ztab-field1,
               field2 TYPE ztab-field2,
    *your own fields here:
               field TYPE i,
               field(30) TYPE c,
               END OF ty_itab.
    work area
    DATA : gw_itab TYPE ty_itab.
    internal table
    DATA : gt_itab TYPE TABLE OF ty_itab.
    hope this helps
    ec

  • Java5: Can't find a way to get rid of warnings about generic types

    Hi all,
    i have this method:
        public static void insert(List list, int index, Object obj) {
            list.add(obj);
            int j = list.size() - 1;
            for (; j > index; j--) {
                list.set(j - 1, list.get(j));
            list.set(index, obj);
        }I get 3 warnings. All about:
    Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized
    I can't find a way to rewrite this method (Java5), that i get no warnings compiling it and calling it with:
    List<AnyClass> list = new ArrayList<AnyClass>();
    list.add(new AnyClass());
    AnyClass ac = new AnyClass();
    insert(list, 0, ac);May be you know another way to insert an element to a List?
    Thanks

    Never tried it and do not have 5.0 installed to test
    it, but what if you define the ArrayList as follows?
    List<Object> list = new ArrayList<Object>();
    That should get rid of the warnings.

  • JLS3: Scope of type parameter and inner class declaration

    The following code:
    class Foo<E>
      class E
        E foo()
          return this;
    }produces this error message:
    $ javac Foo.java
    Foo.java:7: incompatible types
    found   : Foo<E>.E
    required: E
          return this;
                 ^
    1 errorApparently, the type parameter E of the outer class Foo shadows the inner class declaration E. An alternative way to check is to create a new E() in this method, which results in an error message about using a type parameter where a type is expected.
    Of course this code is sick, but I would like to know where this is defined in the JLS3, since I cannot find out in which way this shadowing works. What I've found until now:
    Page 179:
    "The scope of a class' type parameter is the entire declaration of the class."
    Page 190:
    "The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, ... "
    Page 132:
    "If a type name consists of a single Identifier, then the identifier must occur in the scope of exactly one visible declaration of type with this name, or a compile time error occurs."
    Section 6.3.1 (Shadowing declarations) specifies the shadowing rules, but does not mention type parameters.
    Any help is appreciated.

    The current behaviour in eclilpse seems to be the one we get if the bug in javac is fixed as described.
    This code compiles
    public class Shadow1 {
         class Foo<E>
           class E
              E foo()
               return this;
    }but this code
            Foo<E>.E foo()
               return this;
             }shows
    Type mismatch: cannot convert from Shadow1.Foo<E>.E to Shadow1.Foo<Shadow1.Foo<E>.E>. E
    Not sure if this error message is correct.

Maybe you are looking for