Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of C++ variadic templates in Java

Tags:

java

I wish to write a generic type safe observer in Java. In C++, I can easily do it by using variadic template from c++11, like following:

class Observer<typename... T>
{
    void update(T... args);
};

Now, in java, the best I could do is:

class Observer<T>
    {
        void update(T args);
    };

Now, update can not take multiple arguments of different types like in C++. Could someone suggest a solution to this problem?

Thanks in advance.

like image 635
Aarkan Avatar asked Oct 15 '13 14:10

Aarkan


People also ask

Does Java have variadic functions?

Core Java bootcamp program with Hands on practiceMethods which uses variable arguments (varargs, arguments with three dots) are known as variadic functions.

Does Java have templates like C++?

There are no real templates in Java. C++ templates are compile-time entities that are used to generate classes. At runtime, there is no trace of them. In Java, there are parameterized types as part of a mechanism called generics.

What are templates in Java?

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

Can we use templates in Java?

Template Method is a behavioral design pattern that allows you to defines a skeleton of an algorithm in a base class and let subclasses override the steps without changing the overall algorithm's structure.


1 Answers

If all the arguments extend/implement T you can say:

class Observer<T>{
        void update(List<? extends T> args){}
}
like image 167
Lukas Eichler Avatar answered Sep 28 '22 07:09

Lukas Eichler