Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method with no parameter

Tags:

java

generics

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?

like image 813
Thinhbk Avatar asked Jun 04 '12 05:06

Thinhbk


People also ask

Can a non generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

How do you declare a generic method?

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.

What is a generic method and when should it be used?

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.


1 Answers

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.

like image 140
Bohemian Avatar answered Oct 02 '22 12:10

Bohemian