Home > database >  Is possible to create Java generics class depending on int value?
Is possible to create Java generics class depending on int value?

Time:12-09

We can create a generic class in Java like this

public class MyClass<T> {
...

but, now that i'm translating a (very large) C code to Java, i need a class to be different from other depending on its size, like in this c code:

template<size_t size> class MyClass {
...

so every class is a different type, there static members are different, and members like "compare" can only be used with objects with the same size.

Is possible to do this in Java? if not, how would you handle this?

CodePudding user response:

No, you can't use values as parameters instead of a generic type in Java. You should probably just take the size as a parameter in the constructor and implement safety checks taking the size into account.

CodePudding user response:

Sure, but it sucks.

You can model "counting' with a chain of recursive types. Inc<Inc<Inc<Integer>> could represent 3.

It is exceedingly awkward.

Java generics are not C templates. Java generics have a common base implementation and auto write some wrapping code to cast parameterized arguments to/from a common base in a thin wrapper.

C templates generate distinct types.

The design of C templates was to replace code generation and/or hand-rolled C code low level data structures. The goal wad a template class could match or even exceed hand-written C versions (exceed because you can invest more engineering effort into the single template, and reuse it in 100s of spots).

Templates like std::function more closely approach Java generics. While the implementation is dissimilar, here it converts a muriad of types to one interface, hiding the casting from the end user. In C this technique is called type erasure, where std function "erases" all information about the stored callable except what it exposes.

But because Java generics only supports one subtype of type erssure, and C templates support not only more kinds of type erasure but also entitely different metaprogramming techniques that are alien to Java, replacing templates with Java generics is going to consistently run into problems. Only when the C use case happens to perfectly line up with the weaker Java generics does it work right.

(Note that, while weaker, Java generics make type erasure far easier, because they write a bunch of the casting code for you, and type check it. Weaker doesn't mean worse; it often means safer. But mechanically replacing a system with a weaker one often is doomed to failure.)

  • Related