2012Fall求offer比较,美国chem VS 加国ChemE# ChemEng - 化学工程
m*j
1 楼
ClassB1,B2,...,Bn都是ClassA的subclass,现在有某个ClassBi的一个instanceB,
但是我取到它的时候只知道它是A,不知道他具体是哪个B。
e.g.我拿到一个苹果(instanceB),但是现在只知道这是个水果类(ClassA)而不知道
到底是什么水果。我的目的是把instaceB cast成苹果类。
我现在能用reflection取得instanceB的class以及class name,可是不知道怎么才能用
这个信息将instanceB cast成他自己的真实的subclass。因为只有cast后才能用B的某
些方法?我试了如下两种方法都不work。根据(http://
stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-v
ariable-from-one-type-to-another),似乎只能将ClassB1...ClassBn一个一个用ins
tanceof试一遍?
多谢!
code:
ClassA instanceB = xxx.getInstance(yyy); // this is third party API
Class classB = instanceB.getClass(); // this returns the correct subclass of
instanceB
// method 1
instanceB = (classB)instanceB; // this does NOT work
// method 2
Object o = classB.cast(instanceB); // this works, but since the returned is
an Object, I still canNOT use classB methods
但是我取到它的时候只知道它是A,不知道他具体是哪个B。
e.g.我拿到一个苹果(instanceB),但是现在只知道这是个水果类(ClassA)而不知道
到底是什么水果。我的目的是把instaceB cast成苹果类。
我现在能用reflection取得instanceB的class以及class name,可是不知道怎么才能用
这个信息将instanceB cast成他自己的真实的subclass。因为只有cast后才能用B的某
些方法?我试了如下两种方法都不work。根据(http://
stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-v
ariable-from-one-type-to-another),似乎只能将ClassB1...ClassBn一个一个用ins
tanceof试一遍?
多谢!
code:
ClassA instanceB = xxx.getInstance(yyy); // this is third party API
Class classB = instanceB.getClass(); // this returns the correct subclass of
instanceB
// method 1
instanceB = (classB)instanceB; // this does NOT work
// method 2
Object o = classB.cast(instanceB); // this works, but since the returned is
an Object, I still canNOT use classB methods