saga
saga

Reputation: 2113

Reference to a class in java

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]

Upvotes: 2

Views: 95

Answers (2)

AxelH
AxelH

Reputation: 14572

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;

Upvotes: 1

Eugene
Eugene

Reputation: 120848

Something like this:

 Class<String> clazz = String.class
 Class<Cl> clazz2 = Cl.class;
 List<Class<Cl>> list = new ArrayList<>();
 list.add(clazz2);

Upvotes: 2

Related Questions