Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taming the type checker in Java Generics

Tags:

java

generics

I thought I understood Generics pretty well, but apparently I didn't.

Here is the test case of the problem:

import java.util.ArrayList;

class Job<J extends Job<J,R>, R extends Run<J,R>> {}
class Run<J extends Job<J,R>, R extends Run<J,R>> {}

class Job2 extends Job<Job2,Run2> {}
class Run2 extends Run<Job2,Run2> {}

class RunList<J extends Job<J,R>, R extends Run<J,R>> extends ArrayList<R> {}

class Foo {
    // #1 problem
    public void test1(RunList<Job,Run> why) {}
    // #2 this doesn't work either
    public void test2(RunList<Job<Job,Run>,Run<Job,Run>> why) {}
    // #3 this works
    public void test3(RunList<Job2,Run2> why) {}
}

The compiler doesn't allow the test1 method above, saying that "Job" is not within its type bounds. I kinda sorta understand it --- Job as a raw type doesn't extend Job<Job,Run>, hence the error. In contrast, test3 works.

Now, the question is, how do I make this work? I've tried #2, but that doesn't work either. The problem I suppose is really similar with #1 --- Job<Job,Run> is not within the bounds because its type argument Job is a raw type.

Does anyone know how to make the type checker happy, other than resorting to the raw type? Or is it just not attainable in the Java type system?

like image 475
Kohsuke Kawaguchi Avatar asked Aug 10 '10 01:08

Kohsuke Kawaguchi


1 Answers

Maybe:

public <J extends Job<J, R>, R extends Run<J, R>> void test(RunList<J, R> why) {}
like image 97
nairb774 Avatar answered Nov 05 '22 04:11

nairb774