8

I have some classes (Car, Motorcycle, Train ... etc) that extends from class Vehicle. From another Class I need to create an ArrayList of Classes for access only to those that inlude the ArrayList.

The concept is similar to this, but obviously it doesn't work;

ArrayList<Class> vehicleType=new ArrayList<Class>();
vehicleType.add(Class.forName("train"));

How can I solve it ? Thanks

8
  • 2
    There's no reason why this shouldn't work. What error messages, if any, are you getting? Commented Oct 25, 2011 at 18:19
  • Class.forName("Train") perhaps? Case sensitive? Commented Oct 25, 2011 at 18:20
  • 2
    I'm not familiar with java, but does ArrayList<Vehicle> do what you want? Commented Oct 25, 2011 at 18:20
  • Maybe the class name is Train and your forName() call specified train, which doesn't match in the first letter? Commented Oct 25, 2011 at 18:21
  • 1
    A warning is not a problem. To get it to actually work, follow Dave's answer. I guess the warning you get is about the unparameterized Class reference. Use this: ArrayList<Class<? extends Vehicle>>. Commented Oct 25, 2011 at 18:30

5 Answers 5

11

Most answers follow your suggestion of using Class.forName(), though that's not necessary. You can "call" .class on the type name.

Take a look at this JUnit test:

@Test
public void testListOfClasses() {

    List<Class<?>> classList = new ArrayList<Class<?>>();

    classList.add(Integer.class);
    classList.add(String.class);
    classList.add(Double.class);

    assertTrue("List contains Integer class", classList.contains(Integer.class));
}

I would expect for your need the list would be of type Class<? extends Vehicle>

Sign up to request clarification or add additional context in comments.

Comments

3

If you're going to use the class loader (Class.forName), you need to use the fully qualified class name, i.e. Class.forName("com.package.Train");, exactly as you would reference it from the command line.

Comments

2

Try:

ArrayList<Class<? extends Vehicle>> vehicleType=new ArrayList<? extends Vehicle>();
vehicleType.add(Train.class);

It will make sure that all classes added to vehicleType extend Vehicle. And, that class Train actually exists.

It's rarely necessary to use classes that way. Try finding a simpler way of solving your problem.

Comments

1

Class.forName("Train") perhaps? Case sensitive?

Comments

0

If "train" is the simple class name then this will do the job

vehicleType.add(Class.forName(train.class.getName()));

Anyway while you don't tell us what is the error (or exception) message we cannot help further.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.