在Java中,在函数内部实例化一个类。

huangapple go评论84阅读模式
英文:

Instantiate a class inside a function in Java

问题

我正在尝试创建一个函数,该函数将一个2D数组填充满一些对象。我的函数如下:

void funcName(Element el){
    container[0][0] = new el(args);
}

唯一的问题是,Element 是一个抽象类,因此当我尝试实例化一个对象时,Java会给我一个错误。我想要做的是实例化作为 Element 扩展构建的类的对象(例如,类 B 扩展自 Element)。是否有一种方法将这些类作为参数传递,并让我的函数相应地创建它们呢?

英文:

I'm trying to create a function which fills a 2d array with some objects. My function looks like this:

void funcName(Element el){
    container[0][0] = new el(args);
}

The only issue here is that Element is an abstract class, and so Java gives me an error when I try to instantiate an object. What I am trying to do is instantiate objects of classes which are built as extension to Element (i.e Class B extends Element). Is there a way to pass those classes as an argument, and have my function create them accordingly?

答案1

得分: 1

抽象类:

public abstract class Element {

    public abstract void myMethod();

}

具体类:

public class ArrayElement extends Element{

    @Override
    public void myMethod() {
        System.out.println("Hello!");
    }

}

调用必须按以下方式进行:

public class Main {

    public static void main(String[] args) {
        Element element = new ArrayElement();
        calculate(element);		
    }

    // 这种语法允许您使用从Element类继承的任何类,因为它保证可转换为您需要的类型。称为泛型。
    public static <T extends Element> void calculate(T element){
        element.myMethod();
    }

}
英文:

The abstract class:

public abstract class Element {

	public abstract void myMethod();
	
}

The concrete class:

public class ArrayElement extends Element{

	@Override
	public void myMethod() {
		System.out.println(&quot;Hello!&quot;);
	}

}

The calling must be done in this way:

public class Main {
	
	public static void main(String[] args) {
		Element element = new ArrayElement();
		calculate(element);		
	}
	
    // This syntax will let you use any class that extends from the Element class, since it guarantees that is convertible to the type that you need. Are called generics.
	public static &lt;T extends Element&gt; void calculate(T element){
		element.myMethod();
	}

}

答案2

得分: 0

尝试一下这个。

    static abstract class Element {} 
    static class B extends Element {}

    static void funcName(Class<? extends Element> cls)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException,
            NoSuchMethodException, SecurityException {
        Element[][] container = new Element[1][1];
        container[0][0] = cls.getConstructor().newInstance();

以及

    funcName(B.class);

或者

    static void funcName(Supplier<Element> s) {
        Element[][] container = new Element[1][1];
        container[0][0] = s.get();  // 等同于 `new B()`
    }

以及

    funcName(B::new);
英文:

Try this.

static abstract class Element {} 
static class B extends Element {}

static void funcName(Class&lt;? extends Element&gt; cls)
        throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException,
        NoSuchMethodException, SecurityException {
    Element[][] container = new Element[1][1];
    container[0][0] = cls.getConstructor().newInstance();

and

funcName(B.class);

Or

static void funcName(Supplier&lt;Element&gt; s) {
    Element[][] container = new Element[1][1];
    container[0][0] = s.get();  // is equivalent to `new B()`
}

and

funcName(B::new);

huangapple
  • 本文由 发表于 2020年8月28日 08:43:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63625924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定