1

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?

JD009
  • 49
  • 7
  • Well you shouldn't capitalize cityT, but it's hard to help when we have no idea what it actually is that you are trying to do. – Andy Jan 13 '12 at 04:00
  • do you mean something like a var in c# or javascript? – tehdoommarine Jan 13 '12 at 04:01
  • 1
    If you want to be able to pass only a String or an int, why not just have two constructors, `CityOp(String s, String t)` and `CityOp(String s, int i)`? If you create a generic class, then it needs to be able to accept anything, not just a String or int. – Yuushi Jan 13 '12 at 04:03

1 Answers1

1

The question seemed a bit unclear to me. If you're looking to pass in either a String or an int for 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:

public class CityOp<T> {
    CityOp(T cityT, T[] par) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException{
        // Constructor body here
    }
}
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57