this not regular question, please listen explain.
i have object of class animal
. how can transform subclass cat
? this:
animal = new animal(); cat c = (cat) a;
of course, know it's not possible casting directly animal
cat
. don't want manually create new cat
, copy fields animal
it. because have lots of class hierarchies need transform. how can solve general way?
ignoring fact, in example want inverse as-is relation (as in "an apple is-a fruit" vs "a fruit is-an apple") - pointless degree.
but lets imagine case, have make potate look like apple. you'll carve out pulp , put potato apple (i use fruit example here because animals gets bit messy). either called proxying or wrapping.
both techniques can done in java either statically or dynamically.
statically: wrapper:
- create new class, i.e. veggiapplewrapper
- let extend apple (so wraps looks apple)
- define constructor accepts other type (i.e. potato)
- implement/override methods common , delegate calls wrapped object
- implement other methods throwing unsupportedoperationexception
dynamically: proxy:
- you have define interface @ least target type (i.e.
interface apple
) - create proxy instance using proxy
- use
apple
interface in list of implemented interface - implement
methodinvocationhandler
forwarding you, similar wrapper, using reflection - cast proxy
apple
alternatives using java's dynamic proxy code generation libraries such cglib or javaassist generate subclass of target type @ runtime, same wrapper implemented proxy.
in order copy values animal cat instance (as animal superclass, fields should common), use reflection api well
for(field f : animal.class.getdeclaredfields()) { f.setaccessible(true) f.set(cat, f.get(animal)); }
this simple example, without exception handling , without considering fields of animal's superclass (getdeclaredfields
retrieves field of this class).
Comments
Post a Comment