Pregunta

I see a new form of type casting in some codes related to JavaFX. The strange thing about it is its functionality that works like type casting but I can't find it under the categories of casting in Java 8 Specifications. This is an example:

    FXMLLoader loader = new FXMLLoader(getClass().getResource("tabs/tabbedWin.fxml"));
    TabbedWinController twc1 = loader.<TabbedWinController>getController();
    TabbedWinController twc2 = (TabbedWinController) loader.getController();

The two last lines seem to do the same job but I wonder what the syntax in front of twc1 mean? It is completely new to me.

If it is type casting why can't I use the statements like int i = <Integer> f; where f is a float variable?

So I'm curious to understand what it is? Since when it has been added to Java? Where I should/can/shouldn't use it?

¿Fue útil?

Solución

This is the way you specify the generic type to a static method. It has been available since generics were released in Java 5.

List<String> emptyListOfStrings = Collections.<String> emptyList();

In your case both forms work fine because the getController method returns an object of the specified generic type.

See here for a discussion.

Otros consejos

It's not related to JavaFX, methods of that form are called generic methods and have nothing to do with casting.

So when you write

loader.<TabbedWinController>getController();

it means that you want getController() to return an object of type TabbedWinController.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top