swyveu
swyveu

Reputation: 135

How to use generic parameters

I'm coming from a Javascript background and I'm having trouble coping with Java being strongly typed, especially when trying to create generic classes.

Say I have a class named Signal that takes a reference and a payload as parameters. The reference will always be of type String, but the type of the payload can vary.

I would like to keep the type of the payload generic, as to be able to pass various classes to it. But, if I understand it correctly, Java does not allow me to declare generic fields!?

So how would I go about it then?

Below is a simple example of what I have in mind. My custom '<#>' symbol is where I'm having trouble. How can I replace it with some proper generic syntax?

class Signal {

    String ref;
    <#> payload;

    public Signal(String ref, <#> payload) {
        this.ref = ref;
        this.payload = payload;
    }
}

Or am I going about this the wrong way?

Are there betters ways of dealing with parameters of which the type is not known in advance?

All info appreciated!

Upvotes: 0

Views: 416

Answers (1)

Fureeish
Fureeish

Reputation: 13424

Java does allow generic fields. You are looking for:

class Signal <T> { // notice the generic introduction here: <T>

    String ref;
    T payload; // now we can use T to represent any generic type

    public Signal(String ref, T payload) { // same here
        this.ref = ref;
        this.payload = payload;
    }
}

Note that T can be any viable name (similar to naming rules for references).

Usage:

Signal<Double> first = new Signal<>("foo", 2.0);
Signal<String> second = new Signal<>("foo", "bar");

Upvotes: 1

Related Questions