Steve P.
Steve P.

Reputation: 14709

What's the point of using .class objects?

In the past few weeks, I've run into several different peoples' code using .class objects. For example, ArrayList of classes : ArrayList<Class> but how to force those classes to extend some super class?.

I looked them up: http://docs.oracle.com/javase/tutorial/reflect/class/index.html

I'm just wondering why you'd want to use .class objects. I can see getDeclaredFields() and getDeclaredMethods() being potentially useful, but I can't really think of concrete examples as to why I'd actually want to use the .class objects in lieu of something else. Could anyone shed some light on this topic?

Thanks in advance.

Upvotes: 0

Views: 161

Answers (5)

Z&#233;ychin
Z&#233;ychin

Reputation: 4205

Plug-in are a big use for this.

Dynamically load .class files which are in say, your plugins folder and execute some specified function from said files. Then, you can have 0 or more plug-ins and any combination of them installed for your application at a time.

Upvotes: 1

Puce
Puce

Reputation: 38152

Another use case:

InputStream is = MyClass.class.getResourceAsStream("/some/resource/in/the/jar");

Upvotes: 1

m0skit0
m0skit0

Reputation: 25874

I think you misunderstood the concept. Class class has nothing to do with compiled classes (.class).

Class is a class that represents a Java class internal structure, such as fields, methods, etc... This is a compile-time entity, which you can use in your code (even before compiling).

.class is a compiled Java class file, which is Java bytecode. This is not a "code" entity (you cannot use it as a class or object in your code -besides as any file-) and it is not available before compilation.

Reflection (Class is part of the reflection package) is useful when you want to do advanced stuff with the code, like manipulating it, accessing its members, getting information from it, etc...

A typical example where you want to use reflection is making a Java debugger. Since any code can be run on the debugger, you need reflection to get information about the object instances and their structure and show this to the user.

Upvotes: 3

austin
austin

Reputation: 5876

Reflection is one reason to use it. Another good example is dynamically constructing objects at runtime.

For example, the Spring framework uses configuration files that contain the names of Java classes. Somewhere in that code, Spring needs to build object instances of those classes. In this way, the objects are created without the compiler needing to know anything about the Java classes at compile time.

Upvotes: 3

piokuc
piokuc

Reputation: 26204

This can be useful when developing an interpreter of a scripting language running on JVM, which has an ability to call Java methods.

Also, might be useful in a system allowing for plugin extensions.

Upvotes: 1

Related Questions