import java.util.hashmap; import java.util.map; public class parent { } public class child1 extends parent { private string id; private string name; // getter & setter } public class child2 extends parent { private string id; private string name; // getter & setter } public class demo { public child1 copytoc1(map m, child1 c) { c.setid(m.get("id")); c.setname(m.get("name")); } public child2 copytoc2(map m, child2 c) { c.setid(m.get("id")); c.setname(m.get("name")); } public static void main(string args[]){ demo d =new demo(); map m=new hashmap(); m.set("id","1"); m.set("name","1name"); d.copytoc1(m,new child1); m.set("id","2"); m.set("name","2name"); d.copytoc1(m,new child2); } } i want avoid copytoc1 , copytoc2 methods tied object type want write generic copy method public t copy(map m, t t) cannot make work. how avoid dry here.
note:i using jdk7
you won't repeat not having different classes different children.
a class type of object. can have more children having multiple instances of 1 type of child.
here's version of code compiles , seems want do:
import java.util.hashmap; import java.util.map; public class demo { public static class parent { } public static class child { private string id; private string name; } public void copytochild(map<string, string> m, child c) { c.id = m.get("id"); c.name = m.get("name"); } public static void main(string args[]) { demo d = new demo(); map<string, string> m = new hashmap<>(); m.put("id", "1"); m.put("name", "1name"); d.copytochild(m, new child()); m.put("id", "2"); m.put("name", "2name"); d.copytochild(m, new child()); } }
Comments
Post a Comment