Web3J - Raw use of parameterized class 'Type'

45 views Asked by At

I am using this dependency

<!-- https://mvnrepository.com/artifact/org.web3j/core -->
<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.10.3</version>
</dependency>

And I have this code:

Function function = new Function(
    "functionName",
    List.of(),
    List.of(
        new TypeReference<DynamicArray<Uint112>>(){},
        new TypeReference<DynamicArray<Uint112>>(){},
        new TypeReference<DynamicArray<Uint160>>(){},
        new TypeReference<DynamicArray<Uint24>>(){}
    )
);

//here I receive the warning
List<TypeReference<Type>> outputParams = function.getOutputParameters();

At the last line I receive the warning Raw use of parameterized class 'Type'.

The code works perfect and I know what means the warning, but in this specific case I don't know how to fix it.

Someone has any idea how to fix that warning?

1

There are 1 answers

2
jaragone On

The warning is raised because Type is a raw type. You may use wildcards (?) if the exact type parameter is not known or if it can vary, as follows:

List<TypeReference<? extends Type>> outputParams = function.getOutputParameters();

Difference:

  • TypeReference: This signifies that the parameterized type is exactly Type, which disregards the type safety benefits of generics (because Type is a generic class and should be parameterized).
  • TypeReference<? extends Type>: This signifies that the parameterized type is an unknown subtype of Type, which allows you to utilize objects of different subtypes of Type while still maintaining type safety.

But one might think that by specifying Type as a generic parameter, we're already dealing with an object of type Type, aren’t we? What is the significance or benefit of using ? extends Type in this context?"

Suppose there is a subtype of Type called CustomType.

  • If you use TypeReference, you are not allowed to use it for TypeReference, even though CustomType is a Type.

  • If you use TypeReference<? extends Type>, you can use it for
    TypeReference without a problem, because CustomType is a subtype of Type.

Example:

TypeReference<? extends Type> ref1 = new TypeReference<CustomType>()    {};  // Allowed 
TypeReference<Type> ref2 = new TypeReference<CustomType>() {};  // Compilation error