3

How can we restrict the client code to pass only certain types of data to instance variable. At some level we can achieve with generics using super and extend keyword. But the limitation with this approach is to single datatype only.

I feel Compile time annotation is the only way to solve the given problem.

Here is my class definition.

// The type parameter T should be instantiated as Boolean or Integer.
public class SampleClass<T> {

    private String name;

    private T value;

    public SampleClass(String name, T value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return this.name;
    }

    public T getValue() {
        return this.value;
    }

}

Now, if anyone wants to create the object of this class, then they to specify the Type for value variable.

i.e

SampleClass<Integer> s = new SampleClass<Integer>(); 

Now, Question is if I want to restrict the user so that he/she can create objects with certain supported type only. For example, I want to support only 2 dataypes (Integer, Boolean) for the above class

So below are valid scenarios

SampleClass<Integer> i = new SampleClass<Integer>(); // So now this object will work for integer value
SampleClass<Boolean> b = new SampleClass<Boolean>(); // So now this object will work for boolean value

Now if anyone tries to create objects with other data, then the program should show the compile time error.

How can I achieve with compile time annotation? Is there any annotation already exist?

mernst
  • 6,276
  • 26
  • 41
sunshine
  • 31
  • 2
  • What you are looking for (``) is called *union types* and is unfortunately not supported directly in Java (except for throwables in catch blocks). An annotation is maybe a good workaround. – Thilo Dec 04 '19 at 12:29
  • Here is one approach: https://stackoverflow.com/a/51092768/14955 – Thilo Dec 04 '19 at 12:30

0 Answers0