Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force parameterized type as constructor parameter to be correct

Tags:

java

generics

I have been searching for quite a while on this, and nothing really comes close to what I need.

Example code:

public class MyQueue<E extends Delayed & Serializable> extends DelayQueue<E> {
    private Class<E> mClass;
    public MyQueue(Class<E> type) {
        super();
        mClass = type;
    }
}

MyQueue is created like: MyQueue q<MyObj> = new MyQueue<MyObj>(MyObj.class);.

My question: How can I write the constructor in such a way, that the parameter "type" is of the proper parameterized type "E extends Delayed & Serializable"?

I hope I have explained myself allright.

Thank you in advance for any assistance.

Edit: From the answers and remarks I was at first unable to select a proper answer. So for the first time I shall try to enhance my question with what I wanted in the first place, and what I am ending up with now. Eg answering in the original post what I have found.

Obviously what I need to know, is the class of the parameterized type E on construction time. For transparancy, the queue is using the E class name (being MyObj) to pass to a backing store. After a lot of reading I came to understand that I could not get at this information easier because of type erasure. I was forced to pass the class not only as a parameterized type, but also as a constructor variable.

I was afraid I could, by accident, call the constructor as such (MyObj and OthrObj both implement Delayed & Serializable):

MyQueue q<MyObj> = new MyQueue<MyObj>(OthrObj.Class);

My better question should have been: How can I write the constructor in such a way, forcing the constructor variable E to match the parameterized type E?

It would have made so much more sense, and it probably would have been easier to understand what I have written. Technically most of you are right in some sense, and after testing many of the variations, I came to the conclusion I have already done so giggles sorry seh and Tnem are completly right and both deserve the credits.

like image 329
djBo Avatar asked Dec 18 '25 16:12

djBo


1 Answers

What you have written is what you have specified, the type parameter will be enforced to be of type Delayed & Serializable. I can't see what is wrong here...

like image 193
mark-cs Avatar answered Dec 20 '25 08:12

mark-cs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!