Question

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);
}
Was it helpful?

Solution

Try BeanUtils.copyProperties from Apache commons library.(Same thing available in Spring's BeanUtils class.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top