How can I create an object that is the type a user has passed in? Here is an example of what I mean:
import java.util.*;
public class ObjInit {
public Object initObjOfType(String type) {
Object obj;
if(type.equals(/*Type of Object*/)) {
obj = new /*Type of Object*/();
}
return obj;
}
}
A problem I encountered when attempting this is that the type of object is casted to an object, and I do not want that. I want to make it so no casting is needed so it is all automated.
I am not sure I am using this correctly. I used your code, and It gives me an error, saying myObject can not use nextLine() because it is of type Object.
If you want to create an object of the type specified by a user in Java, you can use reflection to accomplish this. Here is an example implementation of your initObjOfType method using reflection:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public Object initObjOfType(String type) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> clazz = Class.forName(type);
Constructor<?> constructor = clazz.getConstructor();
return constructor.newInstance();
}
public static void main(String[] args) {
// your code here
}
}
}
}