Is it possible to create a class that contains objects of the type Class
?
I know that the class java.lang.class
is final and cannot have sub classes.
Asked
Active
Viewed 63 times
0

Mark Rotteveel
- 100,966
- 191
- 140
- 197

James S.
- 5
- 3
-
Are you asking if a class can containg fields like `Class someClass` – mightyWOZ Jan 11 '20 at 16:56
-
4What prevents you from creating your own class with a java.lang.Class as a field? java.lang.Class is a class like any other one and can be used as any other class. – m0skit0 Jan 11 '20 at 16:57
-
The fact that class `java.lang.Class` is `final` doesn't prevent you from creating fields of type `Class` in your own class (in other words: this doesn't have any implications for your question). – Jesper Jan 12 '20 at 09:58
1 Answers
1
Class
is an Object
just like String
or Integer
. As such, you could keep a collection of Class
objects in a List
, for example.
public class ClassTest {
public static void main(String[] args) {
Collection<Class> classes = new ArrayList<>(3);
classes.add(String.class);
classes.add(Integer.class);
classes.add(ClassTest.class);
for (Class storedClass : classes) {
System.out.println(storedClass.getSimpleName());
}
}
}
This returns
String
Integer
ClassTest
If you want to keep these Class
references within your own class
, you can save the values within the instance (or static) fields and return these as appropriate to your needs, e.g.
public void ClassStore {
private Class myFavouriteClass; // Set in constructor or setter method
private List<Class> otherClasses; // Set in constructor or setter method
...
public Class getMyFavouriteClass() {
return myFavouriteClass;
}
public List<Class> getOtherClasses() {
return otherClasses;
}
}

Ekos IV
- 337
- 1
- 10
-
Good answer. I would add a mention that `Class` objects are routinely passed as arguments. Example: `myResultSet.getObject( 1 , OffsetDateTime.class ) ;` ([Javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/ResultSet.html#getObject(int,java.lang.Class))) – Basil Bourque Jan 11 '20 at 17:45
-
1In this case, one should write `Class>`. See https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it. – VGR Jan 11 '20 at 18:53