Java - Type Alias in Java

Subscribe Send me a message home page tags


#java  #type alias 

I came across this interesting blog post. It discusses the idea of implementing type alias in Java. Java does not support type alias but it seems that we can achieve the same effect by making the class generic. According to the there-is-no-free-lunch principle, we need to pay some price. It turns out that we need additional codes at the caller site.

Here is a sample code that shows how we can use Sequence to represent a list of type T elements in a user-defined class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package language;

import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

import java.util.LinkedList;
import java.util.List;

public class TypeAliasDemo {

    @ToString
    @Builder
    public static class Node {
        private String name;
        private int value;
    }

    @Getter
    @Builder
    public static class MyClass<T, Sequence extends List<T>> {
        final Sequence sequence;

        public void testCreation() {
            // When creating a Sequence instnace, we need a manual cast.
            final Sequence instance = (Sequence) new LinkedList<T>();
            System.out.println("Successfully create a Sequence instance.");
        }

    }

    public static void main(String[] args) {
        final Node node = Node.builder()
                .name("node1")
                .value(20)
                .build();

        final List<Node> nodes = new LinkedList<>();
        nodes.add(node);

        // At caller site, we now need to specify the type information.
        // This is the cost we pay to be able to use alias in the user class script.
        final MyClass<Node, List<Node>> instance = MyClass.<Node, List<Node>>builder()
                .sequence(nodes)
                .build();

        for (Node item : instance.getSequence()) {
            System.out.println("Node in LinkedList: " + item);
        }

        instance.testCreation();
    }
}

Here is the output;

Node in LinkedList: TypeAliasDemo.Node(name=node1, value=20)
Successfully create a Sequence instance.

This technique is quite useful if user-defined class is used as a singleton in the codebase. It can greatly improve code readability. However, if we need to create multiple instances of the user-defined class in different places, then using generic to mimic type alias may not be a good idea.

----- END -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png