As the title says. I don't really like Java's old-fashioned typecast syntax. It's a dynamic data manipulation, but I have to use a mysterious syntax. Is it derived from C language? This is where I want to write functionally. First of all, from the example. I think there are two ways to write it.
SomeClass instance = (SomeClass) anotherClassInstance; // 1
SomeClass instance = SomeClass.class.cast(anotherClassInstance) // 2
No. 1 is the one you want to avoid, No. 2 is good, but one line tends to be long. So I thought about this.
public class As {
public static <T> T of(Object value) {
return (T) value;
}
}
If you use this, you can write fairly neatly as shown below.
SomeClass instance = As.of(anotherClass);
If you are using lombok, it looks like this.
val instance = As.<SomeClass>of(anotherClass);
that's all!
Recommended Posts