[英]How to create an object from parameter?
假设我有这样的事情:
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();
}
}
您可以使用反射和泛型。
如果以这种方式执行此操作,则必须确保每个类都有一个(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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.