How do I declare an object of a variable type? I know that I need to use generics, I’ve written this code but I’m not sure if it makes sense for what I want to do.
I want to declare an object of a variable type, and pass either an int or a string as a parameter for the object constructor.
Here is the code I wrote:
CityOp(String CityT, Class<?>[] par) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException{
Class<?> co = Class.forName(CityT);
Op.getDeclaredConstructor(par);
}
Does the code make sense?
The question seemed a bit unclear to me. If you’re looking to pass in either a
Stringor anintfor the first parameter, and the second parameter must match the type of the first, then you can use a generic class to accomplish this, as follows: