سؤال

In this gemfire tutorial

I am not able to interpret this generic declaration:

people = cache.<String, Profile>createRegionFactory(REPLICATE)
      .addCacheListener(listener)
      .create("people");

What is the significance of the generics the way they have been used in this code snippet?

هل كانت مفيدة؟

المحلول

The <String, Profile> after the cache. is an explicit type argument. Explicit type arguments are often used when the compiler can't properly infer the type argument, in which case, you explicitly tell it to infer the type argument as the one you passed in the angular brackets before the method name.

For example, suppose you have a method:

public <T> void someMethod(T param1, T param2) {
    // body
}

Now if you invoke this method as:

obj.someMethod(12, "abc");

then you would expect that the invocation should give you a compiler error, as you are passing different types to the same type parameter. But it doesn't. In fact, the type T is inferred as:

T: Object & Serializable & Comparable<? extends Object&Serializable&Comparable<?>>

But, you might want compiler to infer the type argument as Object. So, how would you do that? There you need an explicit type argument:

obj.<Object>someMethod(12, "abc");

.. and now the type T will be inferred as Object.


So, in your case, I would guess createRegionFactory(REPLICATE) method would be returning a parameterized type with unexpected type parameter, say - SomeType<Object, Object>, because the compiler couldn't infer the type parameter, may be because there is not enough context. But you wanted the further method chain - addCacheListener(listener) to be invoked on the parameterized type with type parameter <String, Profile>.

So, to tell the compiler explicitly to return the parameterized type with a certain type parameter, you give them explicitly with method invocation as:

cache.<String, Profile>createRegionFactory(REPLICATE)
     .addCacheListener(listener)...

Now, the addCacheListener(listener) would be invoked on SomeType<String, Profile> instead of SomeType<Object, Object>


References:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top