Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instances of dynamically given classes in Java

I need a function to create instances of a dynamically given class in java.

I had found many samples but in all of them, the class to be instantiated was known before runtime.

There are user defined classes:

class Student { //some code }
class Teacher { //some code }
class Course { //some code }

What I need is

List<class> MyFunction(<class>) {

  List<class> items = new ArrayList<class>();

  for(int i = 0; i < 5; i++) {

    create_a_new_class_instance;

    items.add(new_created_instance);
  }

  return items;

}

How will I use

List<Student> students = MyFunction(Student);
List<Teacher> teachers = MyFunction(Teacher);
List<Course> courses = MyFunction(Course);

Hope someone helps.

This is my first question in Stackoverflow, sorry for any inconvenience.

Utku

like image 661
Utku Avatar asked Dec 06 '22 15:12

Utku


1 Answers

In Java 8, you can use a method reference or lambda expression in order to create instances of classes dynamically without using reflection.

public static <T> List<T> myFunction(Supplier<T> supplier) {
    return Stream.generate(supplier)
                 .limit(5)
                 .collect(Collectors.toList());
}

You would call it like:

List<Student> students = myFunction(Student::new);

If you're not familiar with streams, the imperative equivalent is:

public static <T> List<T> myFunction(Supplier<T> supplier) {
    int size = 5;
    List<T> list = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
        list.add(supplier.get());
    }
    return list;
}
like image 111
4castle Avatar answered Feb 13 '23 03:02

4castle