I create a generic method without parameter, some thing like:
private <T> TableCell<T> createTableCell(){
return new TableCell<T>();
}
So, in my program, how to call this method for a concrete type?
Yes, you can define a generic method in a non-generic class in Java.
A Generic class can have muliple type parameters.
Generic Methods All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.
Usually, the type is inferred, but you can specify the type with this syntax:
Note: You have an error in your method's definition - it had no return type:
private <T> TableCell<T> createTableCell(){
return new TableCell<T>();
}
Here's how you can call it:
TableCell<SomeType> tableCell = myObject.<SomeType>createTableCell();
If you method doesn't access any fields, consider making it a static
method, which you would call like:
TableCell<SomeType> tableCell = MyClass.<SomeType>createTableCell();
As an aside, when you use this syntax, many will marvel at your "eliteness" - it's a syntax not often seen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With