generics calling constructor
<p>I am trying to do something I would not normally do, it is a bit odd, but I'd like to make it work.  Essentially I have a factory that has to create objects by calling the constructor with different types of data (A and B take different types in the code below).  I seem to have gotten my self stuck going down the generics route (I do need the code to be as compile time typesafe as possible).  I am not opposed to writing the code differently (I'd like to keep the idea of the factory if possible, and I do not want to have to add in casts - so the "data" parameter cannot be an "Object").</p>

<p>Any thoughts on how to fix the code with generics or an alternative way of doing it that meets my requirements?</p>

<p>(Technically this is homework, but I am the instructor trying out something new... so it isn't really homework :-)</p>

<pre><code>public class Main2
{
    public static void main(String[] args) 
    {
        X&lt;?&gt; x;

        x = XFactory.makeX(0, "Hello");
        x.foo();

        x = XFactory.makeX(1, Integer.valueOf(42));
        x.foo();
    }

}

class XFactory
{
    public static &lt;T&gt; X&lt;T&gt; makeX(final int i,
                                 final T   data)
    {
        final X&lt;T&gt; x;

        if(i == 0)
        {
            // compiler error: cannot find symbol constructor A(T)
            x = new A(data);
        }
        else
        {
            // compiler error: cannot find symbol constructor B(T)
            x = new B(data);
        }

        return (x);
    }
}

interface X&lt;T&gt;
{
    void foo();
}

class A
    implements X&lt;String&gt;
{
    A(final String s)
    {
    }

    public void foo()
    {
        System.out.println("A.foo");
    }
}

class B
    implements X&lt;Integer&gt;
{
    B(final Integer i)
    {
    }

    public void foo()
    {
        System.out.println("B.foo");
    }
}
</code></pre>
