2013年9月10日星期二

Beginners ask generic questions .

class CAB
{
A a;
B b;
public CAB (A a1, B b1)
{
a = new A (a1);
b = new B (b1);
}
}
public class templ
{
public static void main (String [] args)
{
CAB y = new CAB (new Integer (1), new String ("abc")) ;

}
}

------ Solution ------------------------------------ --------
need to get / set methods
------ Solution ------------------------ --------------------
a = new A (a1); generics are not new to
------ For reference only ---------------------------------------
templ.java: 7: error : Unexpected type
a = new A (a1);
^
need: class
Found: type parameter A
One, A is a type variable :
A CAB extension has been declared in the class Object
templ.java: 8: error : unexpected type
b = new B (b1);
^
need: class
Found: type parameter B
where , B is a type variable :
B extensions have been declared in the class Object CAB
2 errors
------ For reference only ------------------------------ ---------
really is not new. thank you.

------ For reference only ---------------------------------- -----
which said I need get / set methods ? Here is the constructor really ?

3 floor right, generics when you do not know the specific Class A Class B what type , then I assume you write a class MyClass, did not write a constructor with parameters , you should how to do ? Substitution into becomes new MyClass (a1), this program also how execution ?
So for generic classes only through reflection to obtain a new instance :
A a =(A) a1.getClass().getConstructor(a1.getClass()).newInstance(a1);

it looks a little long-winded , reflections are like this
because we do not know specifically what class A class ( yes, really do not know, because at compile -time type erasure , and God can not know ) ,
so I had to get from a1 class A class object ( class itself is an object belonging to the Class class ) ,
then get the constructor of this class ,
but constructor can be overloaded ah , so we put the parameter type ( class object ) passed in, so that it knows what we want to sign .
Well, now that we have this constructor hands , and now how to do that ? Of course, is to call it passing parameters slightly ( ie, newInstance)
------ For reference only --------------------------- ------------
learning , thank you. Unfortunately, points plus finished. owen1759 Do not blame me.

没有评论:

发表评论