如何从参数创建对象?

时间:2014-04-02 20:35:51

标签: java methods parameters subclass parameterized

让我说我有这样的事情:

public class Projectile
{
     public Projectile(){
     }

     public A(int i, int i2){
     //do stuff
     }
}

public class Bullet extends Projectile
{
     public Bullet(){
     }

     public Bullet(int i, int i2){
     }
}

public class Rocket extends Projectile
{
     public Rocket(){
     }

     public Rocket(int i, int i2){
     }
}

public class Weapon
{
     public Weapon(){
     }

     //This method is wrong and is where i need help
     public void fire(EntityProjectile projectile){
          projectile = new EntityProjectile(1,2);
     }
}

所以我有一个武器,我想把任何射弹放在“火”方法中。我希望能够像这样调用方法

fire(Bullet);
fire(Rocket);

fire(Bullet.class);
fire(Rocket.class);

因此,此方法中的代码不会创建抛射类,而是创建所需的子类。 我知道我可以通过使用不同参数的几个“火”方法来重载方法,但是例如如果我有50个不同的射弹子类,我是否必须制作50个“火”方法?或者有没有办法只有一种方法?

编辑:好的,我刚刚找到了怎么做!

public <T extends Projectile> void fire(Class<T> projectileClass)
{
    try 
    {
        T projectile = projectileClass.getConstructor(int.class, int.class).newInstance(1,2));              
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用反射和泛型。

如果你这样做,你必须确保每个类都有一个(int,int)构造函数。或者您可以更改代码以使用接口/抽象方法。

或让他们将String作为参数并解析字符串。

public class Main {

    public static class Projectile
    {
         public Projectile(){
         }

         public Projectile(int i, int i2){
         }
    }

    public static class Bullet extends Projectile
    {
         public Bullet(){
         }

         public Bullet(int i, int i2){
         }
    }

    public static class Rocket extends Projectile
    {
         public Rocket(){
         }

         public Rocket(int i, int i2){
         }
    }

    public static class Weapon
    {
         public Weapon(){
         }

         //This method is wrong and is where i need help
         public <E extends Projectile> E fire(Class<E> projectile) {
            try {
                return projectile.getConstructor(int.class, int.class).newInstance(1, 2);
            } catch(Exception e) {
                System.out.println("The class " + projectile.getSimpleName() + " does not have a valid constructor");
                return null;
            }
         }
    }

    public static void main(String[] args) {
        Weapon weapon = new Weapon();
        Projectile p = weapon.fire(Projectile.class);
        Bullet b = weapon.fire(Bullet.class);
        Rocket r = weapon.fire(Rocket.class);
    }
}