2

Is it possible to store a reference to a class in java(for example String), similar to python: Java:

class Cl {
    //
}

ArrayList<somethinghere> a;
a.add(Cl);

Python

class Cl:
    pass

A=[Cl]
1
  • 2
    You probably want to use Cl.class. This could be stored in a List<Class<?>> Commented Oct 16, 2017 at 7:59

2 Answers 2

2

Something like this:

 Class<String> clazz = String.class
 Class<Cl> clazz2 = Cl.class;
 List<Class<Cl>> list = new ArrayList<>();
 list.add(clazz2);
Sign up to request clarification or add additional context in comments.

1 Comment

How do i access the methods (like constructor) of a class stored in a reference. Simply doing clazz() gives some errors
1

You can get the Class instance for your class using the static field class.

In your case Cl.class is the value you want.

This can be stored in a variable of type Class<?> or in a List<Class<?>>

Class<?> clazz = Test.class;

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.