Is .class a method or field? - java

Any class in the java has a .class , I want to know .class is a static method or not? Or it is a public static field?
boolean alwaysTrue = (String.class == Class.forName("java.lang.String"));

Its neither.
It's a built-in language feature (a class literal) that looks like a public static final field.

When you write .class after a class name, it references the Class object that represents the given class. .class is used when there isn't an instance of the class available.
For example, if your class is Print (it is recommended that class name begin with an uppercase letter), then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2
It's neither. It's an expression evaluated at compile time to the Class object for that class.

Related

Can you show me what datatype.class means?

I saw code like this:
com.test.model.User.class
I defined User class in com.test.model package
But i don't know .class means..?
I think It isn't a static argument and also I didn't define.
Tell me what .class means and which in class where defined .class i can find .class?
Xyz.class is a syntax provided by Java for obtaining a Class<Xyz> metadata object representing the class corresponding to class Xyz. In your case, it's the User class.
Class<T> objects let you examine the fields and methods of the corresponding class, and in some cases allow you to create instances of the corresponding class. This is part of Java's reflection capabilities.
Class<User> cl = User.class;
for (Method m : cl.getMethods()) {
System.out.println(m.getName());
}
for (Field f : cl.getFields()) {
System.out.println(f.getName());
}
User.class
User.class will return the representation of the User class as a Class object.
The formal term for this expression is the class literal, as referenced in Section 15.8.2 of the Java Language Specification.
When you write .class after a class name, it references the Class object that represents the given class.
For example, if your class is Print (it is recommended that class name begin with an uppercase letter), then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
Source : What does .class mean in Java?

What does .class mean in Java?

What does .class mean in Java? For example, if I created a class called Print. What does Print.class return?
When you write .class after a class name, it references the class literal -
java.lang.Class object that represents information about a given class.
For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
.class is used when there isn't an instance of the class available.
.getClass() is used when there is an instance of the class available.
object.getClass() returns the class of the given object.
For example:
String string = "hello";
System.out.println(string.getClass().toString());
This will output:
class java.lang.String
This is the class of the string object :)
Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.
This '.class' method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.
Check these links (already mentioned above) to get all the details:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
Normally you don't plan on using Reflection right away when you start building your project. It's something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.
If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()
The .class Syntax
If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.
boolean b;
Class c = b.getClass(); // compile-time error
Class c = boolean.class; // correct
See: docs.oracle.com about class
If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.
package test;
public class Test {
public static void main(String[] args)
{
//there is no instance available for class Test, so use Test.class
System.out.println("Test.class.getName() ::: " + Test.class.getName());
// Now create an instance of class Test use getClass()
Test testObj = new Test();
System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());
//For primitive type
System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
System.out.println("int.class.getName() ::: " + int.class.getName());
System.out.println("char.class.getName() ::: " + char.class.getName());
System.out.println("long.class.getName() ::: " + long.class.getName());
}
}
I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.
Adding to the above answers:
Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.
//checking class name using string comparison, only Runtime check possible
if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName()){}
//checking actual Class object for equality, only Runtime check possible
if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass"))){}
//checking actual Class object for equality, but compile time validation
//will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm)
if(myInstance.getClass() == MyClass.class){}
Similarly, the following are also equivalent.
Class<?> myClassObject = MyClass.class; //compile time check
Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check
If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package. MyClass.class is a shorthand method which actually points to the Class object representing MyClass.
As an addendum, some information about Class<?> reference which will be useful to read along with this as most of the time, they are used together.
Class<?> reference type can hold any Class object which represents any type.
This works in a similar fashion if the Class<?> reference is in method argument as well.
Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.
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.
One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T>, therefore:
Class<Print> p = Print.class;
References here:
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
http://docs.oracle.com/javase/tutorial/extra/generics/literals.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2

Using an inner class name and an object name same in Java

In the following code snippet, presumably it appears that it should issue some compilation error but it doesn't:
class Outer {
public static class Inner {
static String obj = "Inner";
}
static Optional Inner = new Optional();
//The (inner) class name and the object name are same.
}
class Optional {
String obj = "Optional";
}
public class Main {
public static void main(String[] args) {
System.out.println(Outer.Inner.obj);
//Refers to the string inside the optional class
}
}
The class Outer has a static class inside it named Inner. Additionally, it declares an object (static) of the class Optional (static Optional Inner = new Optional();)
This object and the class names (inside the class Outer) are same which is Inner. The program displays Optional. The only expression Outer.Inner.obj within main() is expected to display Inner but it doesn't. The actual output is however Optional which is the case of the Optional class.
One way to display Inner is by changing the object name to something else.
static Optional Inner1 = new Optional();
From the output it displays, it appears that the object name (or a variable) is chosen over a type name (the class Inner) because they have the same name. What exact case is applied here?
Paragraph 6.4.2 of the Java Language Specification has some information about the rules that apply in this case.
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of ยง6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.
This refers to paragraph 6.5 Determining the Meaning of a Name, which explains the rules in detail.
In your example, Outer.Inner could refer to the type of the nested class named Inner, or the static member variable Inner. The rules say the variable will be chosen over the type.
Actually the class name is Outer$Inner.
Inner classes are essentially a hack introduced in Java 1.1. The JVM doesn't actually have any concept of an inner class, and so the compiler has to bodge it. The compiler generates class B "outside" of class A, but in the same package, and then adds synthetic accessors/constructors to it to allow A to get access to it.
Checkout the following post:
Java inner class visibility puzzle
Think of the inner class has actually have its own .java file.
That will make it clear to you why it chooses the variable over the Inner class.

Working with the class keyword in Java

I don't really understand how the class keywords work in some instances.
For example, the get(ClientResponse.class) method takes the ClientResponse.class. How does it use this when it gets it, and what are the advantages over just passing an instance of it?
SomeClass.class
returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .
There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.
The keyword is the one that we use to define a class in Java. e.g.
public class MyClass { } /* class used here is one of the keywords in Java */
The class in ClientResponse.class is a short-cut to the instance of Class<T> that represents the class ClientResponse.
There is another way to get to that instance for which you need an instance of ClientResponse. e.g
ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass();
what are the advantage over just passing a instance of it?
In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.
The Class class, which is different from the class keyword, is meta-data describing instances. It tells you about the methods, data members, constructors, and other features of the instances that you create by calling new.
For example get(ClientResponse.class) method takes the
ClientResponse.class how does it uses this when it gets it and what
are the advantage over just passing a instance of it?
You can't pass an instance of ClientResponse to this method; it's expecting meta-data about all instances of ClientResponse. If you passed an instance, you'd expect that the method might change the state of that instance. But passing the meta-data about all instances might allow the method to create a new kind of instance (e.g. a dynamic proxy) or do something else that depends on the meta-data about all instances of ClientResponse. See the difference?
A class is a "blueprint" of the object. The instance is a object.
If we have
public class SomeClass {
int a;
SomeClass(int a) {
this.a = a
}
}
We can have an instance of this class
SomeClass c = new SomeClass(10);
c is an instance of the class. It has a integer a with value 10.
The object SomeClass.class represents a Class.
Here SomeClass.class is a object of the type Class which has the information that SomeClass is
a concrete class with
one constructor
with a integer member variable
and lots more other metadata about the class SomeClass. Note that it does not have a value for a.
You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.
You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.
The very most important fact is - you don't need to have an instance to call the method. It's critically useful in situations when you cannot for some reason instantiate a class, e.g. it's abstract, or have only private constructor, or can only be correctly instantiated by some framework, like Spring or JSF.
You can then call get to obtain an object of a requested type without even knowing where it does come from and how it get's created.
Here ClientResponse.class is an instance of Class<ClientResponse>. In general Class object represents type of an object. When you create new instance:
Object obj = new ClientResponse()
you can retrieve the class (type) of that object by calling:
obj.getClass()
So, why would you pass Class objects around? It's less common, but one reason is to allow some method create arbitrary number of instances of a given class:
ClientResponse resp = ClientResponse.newInstance();
There's a lot of ways Class objects can be used. This is used for Reflection. Below is a link that can help you understand more.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public and static, we can access it using dotted notation along with class name as in your case it is ClientResponse.class.

What happens under the hood when call Class.class.getClass()?

It's not hard to understand String.class.getClass(), which mean return a Class Object that represent the run time class of String Object. But what's going on when calling Class.class.getClass(), can I apprehend it as returning a Class object that represent the run time class of Class object itself? How can this be implemented in Java reflection API?
a Class object that represent the run time class of Class object itself?
Yes.
But String.class.getClass() is the same thing.
String.class already means "the object of type Class that represents the String class". Calling .getClass() on that means "the object of type Class that represents the Class class", because we're calling it on an object of type Class.
If you have an object that is a String, for example "hi mom", then you can reflect it with .getClass(): ("hi mom").getClass() for example. IIRC, this will return the exact same object as String.class in normal circumstances, because there is only one Class object per class (, per ClassLoader in use).
How can this be implemented in Java reflection API?
Every time the bytecode for a class is loaded, a Class object is created and associated with that bytecode. Every object conceptually keeps a "hidden" reference to the Class instance that represents its class, that is automatically set by the constructor. Class objects have this reference set to a Class object that represents the Class class. In particular, the Class object that represents the Class class has a reference to itself.
can I apprehend it as returning a Class object that represent the run time class of Class object itself?
No. Object.class.getClass() is same as Class.class.getClass().
System.out.println(Object.class.getClass() == Class.class.getClass()); // true

Categories