Where is 'class' declared in Java? - java

In the package java.lang I see,
public final class Class<T> extends Object implements Serializable, GenericDeclaration, Type, AnnotatedElement
Where exactly is the 'class' (the word used after 'public final') defined so that it could be used to declare 'Class' (the name of the class in the above declaration)?

It's a Java keyword. Simple as that.
It's not "defined" anywhere....it's part of the language itself.
Keep in mind that this answer is in response to your question below where you are asking about the word class. Based on your subsequent comments to your question, you're not interested in the java specification's BNF style language formalism, so you're asking simply about the word:
Where exactly is the 'class' (the word used after 'public final') defined so that it could be used to declare 'Class' (the name of the class in the above declaration)?

It's a keyword defined in the Java Specification:
8.1. Class Declarations
NormalClassDeclaration: {ClassModifier} class Identifier
[TypeParameters] [Superclass] [Superinterfaces] ClassBody

There are two things in Java by name class.
1) (what you mentioned above) is a class declaration (itself) - as in Javadocs
class MyClass {
// field, constructor, and
// method declarations
}
2) We have a special literal by same name 'class' as well, and as I just found - these two are different things. First is keyword, second is a literal.
class literal ...from Javadoc
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

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.

Why must static access to class be qualified with class name

Why must I qualify a reference to class inside the class that it's defined in? For example:
public class Foo {
private static Logger log = LoggerFactory.getLogger(Foo.class);
}
Why can't I just call LoggerFactory.getLogger(class) since I'm already in the context of the Foo class?
The JLS defines
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.
It wouldn't make the language ambiguous to allow class where an expression is expected to allow the syntax you describe, but it would involve overriding the keyword class to mean both
a kind of declaration
a reference to an instance of type Class.
The syntax you suggest might allow naming the class of an anonymous class, but getClass() would have the same meaning in anonymous classes.
Getting rid of two tokens (the unqualified class name and the .) doesn't provide much value, and it could cause confusion inside an inner class. For example, what is class inside a lambda expression?

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.

About the "class" property/field

When you do:
MyClass.class.someMethod()
What exactly is the "class" field? I can't find it in the API docs. Is it an inherited static field?
I thought reserved keywords were not allowed as entity names.
Please read :
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 a class literal, C.Class, where C is the name of a class, interface or array type, is Class. If p is the name of a primitive type, let B be the type of an expression of type p after boxing conversion (§5.1.7). Then the type of p.class is Class. The type of void.class is Class.
Java Language Specification: 15.8.2. Class Literals
The .class is not actually a field. You can think of is as more of an 'extension' like a file extension. It is a token used to differentiate the Class Object as opposed to an instance of the class.
MyClass is not the name of an object, it's a class name, so this is actually special syntax that retrieves the corresponding Class<MyClass> object for the named class. It is a language feature, not a real property of the MyClass class.
This is documented here:
http://java.sun.com/javase/6/docs/api/java/lang/Class.html

Categories

Resources