如何使用Java中的方法从类动态创建实例

时间:2019-05-15 09:03:15

标签: java

嗨,我是Java的新手, 我想通过调用方法student[0]

从对象student[1]创建一个实例student[2]Class studentcreateStudentInstance ()

任何人都可以帮忙阐明一下

谢谢

2 个答案:

答案 0 :(得分:0)

您应该使用构造函数

public class Student
{
  public Student()
  {
     // Initialize attributes
  }
}

然后在您的方法中调用new Student()以获取实例。

public void createStudentInstance()
{
  Student myStudent = new Student();
  // Do some stuff
  return myStudent;
}

答案 1 :(得分:0)

基本上,您可以通过调用对象的构造函数来创建对象的实例。 如果要创建动态加载的类的实例,请按以下方式进行操作:

public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("Foo").newInstance();

            //or if you want to invoke constructor which takes some arguments:

            Class<?> clazz = Class.forName("Foo");
            Constructor<?> constructor = clazz.getConstructor(int.class);
            constructor.setAccessible(true);
            constructor.newInstance(7);
            constructor.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Foo {
    public Foo() {
        System.out.println("Hello foo!");
    }

    public Foo(int i) {
        System.out.println("Hello foo with number " + i + "!");
    }
}