Lucius Rutilius Lupus
Lucius Rutilius Lupus

Reputation: 169

Java Generic Classes, how to define constructor for possible Parameter types

I am trying to define a Java class which could be used for generic types, but I want to define the constructors for possible parameter types like Character, or an object type I can manually define.

The class I am trying to create is called:

public class Repeated<T> implements Pict {

private T[][] elements;

private double scale;

public Repeated(T[][] elems) {
    elements = elems;
}
}

So I want to add a constructor that adds a Character Array and does something specific if only T is the Type Character. Is it possible? Or should I make this an Interface, then implement it later?

Upvotes: 1

Views: 231

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

You should be able to do this:

public Repeated(T[][] elems) {
    elements = elems;
    boolean isCharacterArrayArray = false;
    if (elems != null) {
        for (T[] elt : elems) {
            if (elt != null && elt.length > 0) {
                isCharacterArrayArray = elt[0] instanceof Character;
                break;
            }
        }
    }
    if (isCharacterArrayArray) {
        // received a Character[][]
    }
}

However, because of type erasure, I don't think you can distinguish these calls:

new Repeated((Character[][]) null);
new Repeated((Integer[][]) null);

without passing some sort of explicit class argument.

EDIT With a class argument, it all becomes much simpler:

public Repeated(T[][] elems, Class<T> cls) {
    elements = elems;
    if (cls.equals(Character.class)) {
        // passed a Character[][]
    }
}

Upvotes: 2

Paul Bellora
Paul Bellora

Reputation: 55213

So I want to add a constructor that adds a Character Array and does something specific if only T is the Type Character

Sounds like a good case for polymorphism:

public class RepeatedChars extends Repeated<Character> {

    public RepeatedChars(Character[][] chars) {
        super(chars);
        //do special stuff
    }

    //other character-specific logic if applicable
}

You could even hide this class as an implementation detail:

public class Repeated<T> implements Pict {

    ...

    private static class RepeatedChars extends Repeated<Character> {
        //see above
    }

    public static Repeated<Character> makeForChars(Character[][] chars) {
        return new RepeatedChars(chars);
    }
}

Upvotes: 2

Related Questions