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.
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 -----
©2019 - 2023 all rights reserved