基于参数返回不同对象的方法

问题描述 投票:-2回答:2

我期望完成的任务(如果可能的话):

在构造函数中输入任何类,并基于该类获取一个新对象

我正在尝试做的简短示例

public class SampleClass {

    private Class classType;

    public SampleClass(Class classType) {
        this.classType = classType;
    }

    public <T> T getObject() {
        // Should return a new object based on the class type
        return null;
    }
} 

预期用途

SampleClass sample = new SampleClass(AnotherSample.class)

AnotherSample another = sample.getObject();

我尝试过的没有运气的事情

return classType.getClass().cast(new Object);

return classType.cast(new Object);

return (this.classType.getClass()) new Object;

return (this.classType) new Object;

以前有可能问过这个问题,如果是这种情况,请指向正确的线程,我真的很感谢

java
2个回答
0
投票

尝试此:

public class Test {

    public static <T> Object foo(Class c) {
        Object ob = null;
        try {
            ob = c.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ob;
    }

    public static void main(String[] args) {
        System.out.println(foo(Sample1.class));
        System.out.println(foo(Sample2.class));
    }
}

class Sample1 {

}

class Sample2 {

}

0
投票

尝试一下,不确定是否正是您要找的东西。

public class SimpleClass<T> {
    private final Class<T> clazz;

    SimpleClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T getObject() throws IllegalAccessException, InstantiationException {
        // Should return a new object based on the class type
        return clazz.newInstance();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.