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

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.

Related

Where is .class defined in Java? (Is it a variable or what?)

There are 2 ways to get a class's Class object.
Statically:
Class cls = Object.class;
From an instance:
Object ob = new Object();
Class cls = ob.getClass();
Now my question is getClass() is a method present in the Object class,
but what is .class? Is it a variable? If so then where is it defined in Java?
That's implemented internally and called a class literal which is handled by the JVM.
The Java Language Specification specifically mentions the term "token" for it.
So .class is more than a variable, to be frank it is not a variable at all. At a broader level you can consider it as a keyword or token.
https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.8.2
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.
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader (§12.2) of the class of the current instance.
That information resides in the class 'file', although classes need not have a physical .class file in the file system. The JVM takes care of making it available from the class definition, as the other answer states.
See also:
https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html

Difference between Interface and Class in Java

As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.
package com.main.service;
public interface SomeService{
public void someMethod();
}
But why below code is allowed in Java?
com.main.service.SomeService.class;
I am using this code to get beans from Spring application context like below:-
SomeService someservice = applicationContext
.getBean(com.main.service.SomeService.class);
The .class syntax at the end of a type (com.main.service.SomeService.class; in this case) references the class literal, which is an object of type Class. You can use this on any Java type, be it a concrete class, abstract class or an interface.
As per the Javadoc from the link above:
Instances of the class Class represent classes and interfaces in a running Java application
This may be confusing if you're new, and are used to having the distinction between class and interface drummed into you, but simply speaking it's how the underlying system works (all classes and interfaces are compiled to bytecode class files.)
You commonly see the syntax used in dependency injection (or other uses where you need to pass the "type" of something around), as it's the easiest way of doing so.
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.
ClassLiteral:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class
The type of C.class, where C is the name of a class, interface, or
array type, is Class.
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
You should look at the Java docs of the method that you are using:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.Class-
Importantly the javadoc states:
Return the bean instance that uniquely matches the given object type,
if any.
NoUniqueBeanDefinitionException - if more than one bean of the given
type was found
So if you have more that one beans extending the interface you will get exception.

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.

What does .class mean after a class name

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.

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