[java] Is there a Java equivalent or methodology for the typedef keyword in C++?

Coming from a C and C++ background, I found judicious use of typedef to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?

This question is related to java c++ c design-patterns typedef

The answer is


Perhaps this could be another possible replace :

@Data
public class MyMap {
    @Delegate //lombok
    private HashMap<String, String> value;
}

Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"

Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.


Typedef allows items to be implicitly assigned to types they are not. Some people try to get around this with extensions; read here at IBM for an explanation of why this is a bad idea.

Edit: While strong type inference is a useful thing, I don't think (and hope we won't) see typedef rearing it's ugly head in managed languages (ever?).

Edit 2: In C#, you can use a using statement like this at the top of a source file. It's used so you don't have to do the second item shown. The only time you see the name change is when a scope introduces a name collision between two types. The renaming is limited to one file, outside of which every variable/parameter type which used it is known by its full name.

using Path = System.IO.Path;
using System.IO;

Kotlin supports type aliases https://kotlinlang.org/docs/reference/type-aliases.html. You can rename types and function types.


In some cases, a binding annotation may be just what you're looking for:

https://github.com/google/guice/wiki/BindingAnnotations

Or if you don't want to depend on Guice, just a regular annotation might do.


There is no need for typedef in Java. Everything is an Object except for the primitives. There are no pointers, only references. The scenarios where you normally would use typedefs are instances in which you create objects instead.


As others have mentioned before,
There is no typedef mechanism in Java.
I also do not support "fake classes" in general, but there should not be a general strict rule of thumb here:
If your code for example uses over and over and over a "generic based type" for example:

Map<String, List<Integer>> 

You should definitely consider having a subclass for that purpose.
Another approach one can consider, is for example to have in your code a deceleration like:

//@Alias Map<String, List<Integer>>  NameToNumbers;

And then use in your code NameToNumbers and have a pre compiler task (ANT/Gradle/Maven) to process and generate relevant java code.
I know that to some of the readers of this answer this might sound strange, but this is how many frameworks implemented "annotations" prior to JDK 5, this is what project lombok is doing and other frameworks.


As noted in other answers, you should avoid the pseudo-typedef antipattern. However, typedefs are still useful even if that is not the way to achieve them. You want to distinguish between different abstract types that have the same Java representation. You don't want to mix up strings that are passwords with those that are street addresses, or integers that represent an offset with those with those that represent an absolute value.

The Checker Framework enables you to define a typedef in a backward-compatible way. I works even for primitive classes such as int and final classes such as String. It has no run-time overhead and does not break equality tests.

Section Type aliases and typedefs in the Checker Framework manual describes several ways to create typedefs, depending on your needs.


If this is what you mean, you can simply extend the class you would like to typedef, e.g.:

public class MyMap extends HashMap<String, String> {}

You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.

public class Apple {
      public Apple(Integer i){this.i=i; }
}

but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.


There is no typedef in java as of 1.6, what you can do is make a wrapper class for what you want since you can't subclass final classes (Integer, Double, etc)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to design-patterns

How to implement a simple scenario the OO way Implementing Singleton with an Enum (in Java) What is difference between MVC, MVP & MVVM design pattern in terms of coding c# Best Practices for mapping one object to another REST API Login Pattern When should we use Observer and Observable? How to implement a FSM - Finite State Machine in Java Function in JavaScript that can be called only once Thread Safe C# Singleton Pattern Repository Pattern Step by Step Explanation

Examples related to typedef

How do I use typedef and typedef enum in C? Overloading operators in typedef structs (c++) What is the difference between 'typedef' and 'using' in C++11? typedef fixed length array Typedef function pointer? C++ template typedef dereferencing pointer to incomplete type uint8_t vs unsigned char typedef struct vs struct definitions Understanding typedefs for function pointers in C