Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Type parameter inference for constructors

843793May 1 2003 — edited May 1 2003
JSR-14 allows the actual type parameter of a parameterized methode to be inferred by the compiler. I would like to suggest to extend this to constructor invocations. Very often the type parameter of a class can be determined by the arguments of a constructor. I'm using generics a lot and to enable this I create static "construct" methods that do actually do this.

An example:
public class Pair<F, S> {

  public static <F1, S1> Pair<F1, S1> construct(F1 first, S1 second) {
    return new Pair<F1, S1>(first, second);
  }

  private F _first;
  private S _second;

  public Pair(F first, S second) {
    super();
    _first  = first;
    _second = second;
  }

  ...
}
The Pair.construct method just invokes the constructor. By using Pair.construct, the value of the F and S parameters can be inferred by the compiler. This saves a lot of code when constructing instances of parameterized classes.

Can you think of any problems?

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 29 2003
Added on May 1 2003
2 comments
110 views