What does .class mean after a class name - java

What does .class mean in, for example, MyClass.class? I understand that when you put the name of a class and the point it is used to access its static fields or methods, but that doesn't relate to '.class'

SomeClass.class gets the Class<SomeClass> type which you can use for programming using the reflection API.
You can get the same type if you have an instance of the class using instance.getClass().
You can check out the documentation here. For example, you can:
get the names of fields and methods, annotations, etc.
invoke methods, get constructor to create new instances of the class
get the name of the class, the superclass, package, etc

When you write .class after a class name, it references the Class object that represents the given class (formally, it is a named class literal). The the type of NombreClase.class is Class<NombreClase>.
E.g., NombreClase.class is an object that represents the class NombreClase on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of NombreClase.
NombreClase obj = new NombreClase();
System.out.println(NombreClase.class.getName());
System.out.println(obj.getClass().getName())

You can add .class to the name of any class to retrieve an instance of its Class object.
When you use Integer.class you reference an instance of Class<Integer>, which is a typed class object.
I always thought this was a field member that got added by the compiler, but it looks like it's really just syntactic sugar.

Related

A method for obtaining an object of type Class

In my textbook I can read:
If T is any Java type, then T.class is the matching class object. For example:
Class cl1 = Date.class; // if you import java.util.*;
Class cl2 = int.class;
Class cl3 = Double[].class;
Later on I'm reading:
The virtual machine manages a unique Class object for each type. Therefore, you can use the == operator to compare class objects. For example:
if (e.getClass() == Employee.class)
Could you help me find anything about this .class field in the documentation.
And another qutstion - I can't understand whether the e.getClass() == Employee.class is the same as e.class == Employee.class. I mean, if it is the same, why the author of the textbook used getClass here in the lefthand expression.
From JLS §15.8.2 - Class Literals:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type (§4.3), is Class.
So, Date.class, int.class are nothing but class literals, which give appropriate Class objects for a class type.
I can't understand whether the e.getClass() == Employee.class is the same as e.class == Employee.class
No, they are not the same. In fact, e.class won't even compile. As per the definition of class literal above, since e is not a type but an object of Employee (I assume that), e.class is not a valid class literal. To get the Class object of a class, using it's instance, you need to use Object#getClass() method.
So, e.getClass() and Employee.class are two different ways to obtain the Class object for Employee class. Both to be used in different circumstances. When you know the class type, use 2nd version, and when you have an instance of your class, use the 1st version.
However, note that in case of inheritance, e.getClass() might not return the same Class object as Employee.class. The former would return the Class object of the actual subclass object, referred by the reference e, whereas the later would always give you Class<Employee>.
If you neither have the instance, nor the class type available, then you can also get the Class object for a class name in String form, using - Class#forName(String) method.
How you get a Class object depends on what you already know. If you have an object referenced by x, you can obtain the Class object for its class by x.getClass(). If you know, when you are writing your code, the name of a type T, you can use T.class to get the class object. There is a third approach, less convenient, that only requires run time access to the class name.
The getClass method is described as one of the Object methods, in the Object API documentation.
Class literals, the T.class form, are described in the Java Language Specification.
The third approach uses one of the static forName methods defined the API documentation for java.lang.Class.

Difference between MyClass.class and Class.forName("className")

We can get class Class object by 3 methods:
MyClass.class
obj.getClass
Class.forName("className")
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
Class.forName("className");
forName is a static method of class "Class".
we require to provide the fully qualified name of the desired class.
this can be used when name of class will come to known at runtime.
ClassName.class;
.class is not a method it is a keyword and can be used with primitive type like int.
when Name of Class is known in advance & it is added to project, that time we use ClassName.class
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
The big difference is when they need it. Since Class.forName accepts a string, the class name can be determined at runtime. Whereas of course, MyClass.class is determined at compile-time. This makes Class.forName useful for dynamically loading classes based on configuration (for instance, loading database drivers depending on the settings of a config file).
Rounding things out: obj.getClass() is useful because you may not know the actual class of an object — for instance, in a method where you accept an argument using an interface, rather than class, such as in foo(Map m). You don't know the class of m, just that it's something that implements Map. (And 99% of the time, you shouldn't care what its class is, but that 1% crops up occasionally.)
Class.forName("className");
It dynamically load the class based on fully qualified class name string.
obj.getClass
Returns the java.lang.Class object that represents the runtime class of the object.
MyClass.class:
A class literal is an expression consisting of the name of a class, interface, array,
or primitive type, or the pseudo-type void, followed by a'.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type is Class<C>.
http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
One important difference is:
A.class will perform loading and linking of class A.
Class.forName("A") will perform loading, linking and initialization of class A.

Java reflecting nested anonymous classes

Why does this code return "class java.lang.Object" ?
Object a = new Object() {
public Object b = new Object(){
public int c;
};
};
System.out.println(a.getClass().getField("b").getType());
Why does the inner-inner type get lost? How can I reflect the c field ?
Edit:
This one works (as pointed out in some answers):
a.getClass().getField("b").get(a) ...
But then I have to invoke a getter, is there any way to reflect c with only reflection meta data?
Because b is declared as Object:
public Object b = ...;
There is a distinction between type of variable (static type) and type of the object referenced by that variable (runtime type).
Field.getType() returns static type of the field.
If you want to get runtime type of the object referenced by the field, you need to access that object and call getClass() on it (since a is declared as Object and therefore b is not visible as its member you have to use reflection to access it):
System.out.println(
a.getClass().getField("b").get(a).getClass());
UPDATE: You can't reflect c without accessing the instance of object containing it. That's why these types are called anonymous - a type containing c has no name, so that you can't declare field b as a field of that type.
Let's look at this line carefully:
System.out.println(a.getClass().getField("b").getType());
First, your take the a variable. It is of some anonymous subclass of the Object. Let's call that class MyClass$1. Okay, so far so good.
Next, you call the getClass() method. It returns the class of a, that is, a description of the MyClass$1 class. This description is not tied to any particular instance of that class, though. The class is the same for all instances, be it a or whatever else (unless different class loaders are used). In this particular case, however, there can be only one instance, because the class is anonymous, but the mechanism is still the same.
Now, from the class, you get the field b. As the class isn't directly tied to any of this instances, the field has nothing to do with a either. It's just a description of what exactly the field a of the class MyClass$1 is.
Now you get its type. But since it isn't tied to any instance, it can't know the runtime type. In fact, if the class wasn't anonymous, you could have numerous instances of MyClass$1, each having different value in a. Or you could have no instances at all. So the only thing getType() can possibly tell you is the declared type of b, which exactly what it does. The b field could in fact be null at that point, and you'd still get Object as the result.
The Field class provides the get() method to actually access that particular field of some object, like this:
System.out.println(a.getClass().getField("b").get(a).getClass());
Now you get something like MyClass$1$1, which is the name of the anonymous class of the object that field b references to, in the a instance.
Why does the inner-inner type get lost?
Because you are getting the type type of the field "b" (Object), not the type of the anonymous inner class of which you assigned the instance to "b".
How can I reflect the c field ?
You could use this
System.out.println(a.getClass().getField("b").get(a).getClass().getField("c"));
instead. This gets the value of the field "b" and it's class, but this only works if "b" is guaranteed be not null.
Doing this seems to indicate a bad design, there might be other ways to archive what you want to do with this. But without knowing the purpose, this is everything I can answer.

what is the Class object (java.lang.Class)?

The Java documentation for Class says:
Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
What are these Class objects? Are they the same as objects instantiated from a class by calling new?
Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?
Nothing gets typecasted to Class. Every Object in Java belongs to a certain class. That's why the Object class, which is inherited by all other classes, defines the getClass() method.
getClass(), or the class-literal - Foo.class return a Class object, which contains some metadata about the class:
name
package
methods
fields
constructors
annotations
and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the #Processable annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class object, which contains metadata about it, that is accessible at runtime.
A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:
public class Car {
public String brand;
}
You can then construct a Class object which describes your "Car" class.
Class myCarClass = Class.forName("Car");
Now you can do all sorts of querying on your Car class on that Class object:
myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field
and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:
Car myCar = new Car();
Class myCarClass = myCar.getClass();
This also works for objects you don't know, e.g objects you get from the outside:
public void tellMeWhatThisObjectsClassIs(Object obj) {
System.out.println(obj.getClass().getName());
}
You could feed this method any java object and it will print the actual class of the object you have given to it.
When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).
Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance(); // is roughly equivalent to = new Car();
You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.
So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.
getClass() is a method that returns an object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:
Class<?> type = (Class<?>) object;
I would also like to add to ColinD 's answer that getClass will return the same object for instances of same type. This will print true:
MyOtherClass foo = new MyOtherClass();
MyOtherClass bar = new MyOtherClass();
System.out.println(foo.getClass()==bar.getClass());
Note that it is not equals, I am using ==.
In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java file you create, when you compile that .java file, the jvm will creates a .class file, this file contains all the information about the class, namely:
Fully qualified name of the class
Parent of class
Method information
Variable fields
Constructor
Modifier information
Constant pool
The list you see above is what you typically see in a typical class. Now, up to this point, your .java file and .class file exists on your hard-disk, when you actually need to use the class i.e. executing code in main() method, the jvm will use that .class file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.
Here is the top level view,
.java --compile--> .class -->when you execute your script--> .class loads into method area --jvm creates class object from method area--> a class object is born
With a class object, you are obtain information such as class name, and method names, everything about the class.
Also to keep in mind, there shall only be one class object for every class you use in the script.
Hope this makes sense
A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method

java class types - what do they mean?

What is the java class type used for? I am confused about what it means and how it is different than declaring an object type:
Class className;
Thanks
There are several uses for a Class object. For example, say I want to create an instance of a class based on some class name stored in a config file.
String className = config.myClass;
Class clazz = Class.forName(className);
Object myClassInstance = clazz.newInstance();
It represents the runtime type of the object. The actual programmatic use of the Class type is often found in reflection and generics.
For example, loading a JDBC driver abstractly with help of Class#forName():
String jdbcDriverClassName = getItFromSomeExternalConfigurationFile();
Class.forName(jdbcDriverClassName);
Or typecasting an generic Object to a beforeknown type:
public static <T> T findAttribute(String key, Class<T> type) {
return type.cast(attributeMap.get(key)); // It's a Map<String, Object>.
}
...which can be used as
SomeType instance = findAttribute("someKey", SomeType.class);
A more extended example can be found here in flavor of a "generic object converter".
Actually, reading the java.lang.Class javadoc, including all of the available methods, should give you an idea what it can be used for.
Class is a special type of Object, i.e Class is a sub class of Object. Every class you define has its own Class object. You can access this as MyObject.class or myInstance.getClass(). In another word, any class you define has a Class attribute where as any class is an Object. I agree it is slightly confusing to a newbie.
javadoc says:
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
You can use it when checking the type of some variable or check for inheritance runtime.
It's also used in reflection, to load dynamically types and execute methods on them.
From the book Thinking in Java:
The Class object
To understand how Run Time Type Information (RTTI) works in Java, you must first know how type information is represented at run time. This is accomplished through a
special kind of object called the Class object, which contains information
about the class. In fact, the Class object is used to create all of the
'regular' objects of your class.

Categories

Resources