简体   繁体   中英

Java downcasting with reflection

I hava a model in Java 1.6 similar to this example:

public class Animal {
  public String color;
}

public class Dog extends Animal {
  public Float height;
}

public class Bird extends Animal {
  public Integer wings;
}

Now I want cast from Animal to anyone child. I know that It's throw a runtime exception for forbidden cast. So I think that it's possible have a children only with the parent fields with the help of a constructor and java reflection. Example:

public class Animal {
  public String color;

  public Animal(Animal old){
    //Set all fields by reflection. but how!
  }
}

public class Dog extends Animal {
  public Float height;

  public Dog (Animal old){
     super(old);
  }
}

public class Bird extends Animal {
  public Integer wings;
  public Bird (Animal old){
     super(old);
  }
}

But how set all de parent fields with reflection?

SOLUTION BY Thinaesh ( https://stackoverflow.com/a/17697270/1474638 ) Thanks!. I'm using Spring so only I need to do in the parent constructor the next:

public Animal(Animal old){
  super();
  BeanUtils.copyProperties(old, this);
}

  public Dog(Animal old){
  super(old);
}

public Bird(Animal old){
  super(old);
}

尝试从Apache commons库访问BeanUtils.copyProperties。(Spring的BeanUtils类中提供了相同的东西。

After getting some clarification through the comments to your question:

All you are doing here is copying values in a class's constructor. There is no need for reflection. Reflection should be avoided unless there is no other way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM