'Does Java have a similar post method diamond operator that C# has?
The Unity project makes frequent use of C# functions that supply a type in a diamond operator after the method name. In the Unity source code it's defined like this:
public static T FindObjectOfType<T>() where T : Object
{
return (T)FindObjectOfType(typeof(T), false);
}
An example of its use:
CanvasRenderer canvas = FindObjectOfType<CanvasRenderer>();
My question is, does the Java language have a similar construct?
Solution 1:[1]
Java has a similar construct, but the name "diamond operator" is reserved (ok, not really 'reserved', but used) for something slightly different.
In the construct
final List<String> stringList = new ArrayList<>();
the <>
is called the "diamond operator" (although "diamond form" would be more correct), and it is a shortcut of the otherwise required term <String>
.
Defining a method with a generic argument or return type looks in Java slightly different from C#:
public final <T,R> R doSomething( final T argument ) { … }
doSomething()
takes an argument of type T
and returns a result of type R
, where R
and T
do not need to be distinct from each other.
Calling doSomething()
may look like this:
final var date = LocalDate.now();
final String result = doSomething( date );
Your C# method FindObjectOfType<T>()
would be declared in Java like this:
public final <T> T findObjectOfType( final Class<T> desiredType ) { … }
and it would be called like this:
CanvasRenderer canvas = findObjectOfType( CanvasRenderer.class );
Solution 2:[2]
Yes. These diamond operators are called generics. Java has them too!
They use the same <> syntax. You can find more information online by searching for "java generics"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | S. ten Brinke |