从方法的参数创建一个新对象

时间:2016-01-15 15:16:41

标签: java

假设您使用方法class获得了copy() x

此方法copy()获得class y 作为参数。 copy(y test)

我的问题是,如何在课堂上创建一个新对象,就像这样:

public void copy(y villy){
       villy v = new villy();
    }

您应该考虑 y 类是父类,并且我将其作为params传递给它的孩子,那么那是什么方法应该做的是创建一个作为参数发送的类的新对象!

1 个答案:

答案 0 :(得分:0)

如果参数是Class引用,并且该类具有不带参数的公共构造函数:

public void copy(Class cls){
   Object obj = cls.newInstance();
}

如果参数是实现Cloneable接口的某个对象,则需要同一类的另一个对象:

public void copy(Cloneable obj1){
   Object obj2 = obj1.clone();
}

编辑20.01.2016

所以我假设每个对象都是一个具有一定能力的口袋妖怪,它有一个方法copy用于复制另一个口袋妖怪的能力。然后我会这样做:

public class FET {

    public static void main(String[] args){

        Pokemon aerodactyl = new Pokemon (new Ability[]{ Ability.WALK, Ability.FLY  });
        Pokemon golduck    = new Pokemon (new Ability[]{ Ability.WALK, Ability.SWIM });

        System.out.println ("aerodactyl = " + aerodactyl);
        System.out.println ("golduck    = " + golduck   );
        System.out.println ();

        golduck.copy (aerodactyl);

        System.out.println ("aerodactyl = " + aerodactyl);
        System.out.println ("golduck    = " + golduck   );      // golduck has now the same abilities as aerodactyl
        System.out.println ();

        aerodactyl.abilities[0] = Ability.EXPLODE;              // change aerodactyl's abilities

        System.out.println ("aerodactyl = " + aerodactyl);
        System.out.println ("golduck    = " + golduck   );      // abilities of aerodactyl have changed but golduck's not
        System.out.println ();

    }

}

enum Ability {
    WALK,
    FLY,
    SWIM,
    TALK,
    EXPLODE
}

class Pokemon {

    public Ability[] abilities;

    public Pokemon (Ability[] abilities) {              // constructor
        this.abilities = abilities;
    }

    public void copy (Pokemon p) {                      // copy abilities of another Pokemon
        abilities = (Ability[]) p.abilities.clone();
    }

    public String toString() {                          // string representation of Pokemon
        String str = "Pokemon";
        if (abilities != null) {
            for(int i = 0; i < abilities.length; i++) {
                str += (i==0) ? ": " : ", ";
                str += abilities[i];
            }
        }
        return str;
    }

}