This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a class literal in Java?
I was going through literals in the Java tutorial where I came across this sentence:
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.
Which doesn't make any sense to me, even though I paid attention to all the other topics prior to this. Can anyone explain in simple language with examples or references?
Instances of the class java.lang.Class represent classes and interfaces in a running Java application. For each class in the application, there is an instance of Class. The SomeClass.class syntax is a way to get from SomeClass to the corresponding instance of Class.
A class literal is just a special type to use when you want to do something involving the class itself, rather than an instance.
Here's a short list of a few things I commonly use this for (not at all comprehensive, but you can get a good idea)
1.) Reflection, you want to instantiate something in run-time that you may not know (perhaps it was stored in a variable of type Class)
2.) You want to check if 2 objects are of the same related type, you can write something along the lines of: B.class.isAssignableFrom(a.getClass());
3.) You want to list all the methods, or public variables within a class, perhaps for documentation.
There are many other uses, but these are the main ones I find myself using in common practice.
Speaking simple language: that thing, which you call class literal is an object which fully describes some class: all its methods, all its fields, all its annotations, class's modifiers and so on. It is needed for creating new instances of that class in runtime.
Short example:
Class x = String.class;
System.out.println(x);
you can use x to create runtime instances of the class it points to or to test the class of an object against it.
It evaluates to be the class identifier of the reference or primitive type's wrapper class. The expression void.class evaluates to the class identifier of the Void class. Same thing with 'String.class'
Related
Actually this is a three part question.
1 I want know to know on what occasions do we use the keyword class. It is obvious that we use it to
define a class. But what is the purpose of using SomeClass.class in a expression?
2 I read on Wikipedia that it can be used instead of the expression new SomeClass().getClass(). But why do we need this when we already can use new SomeClass().getClass() expression?
3 And when do we need to use this SomeClass.class expression in a statement?
I am referring to Anonymous Inner classes and it occurred to me we can't use the getClass() method in a static method.
The following answer from Stephen gives the exact unique answer for this problem.
But what is the purpose of using SomeClass.class in a expression?
It is called a class literal; see JLS 15.8.2.
The purpose is to get the Class object that for the class denoted by SomeClass. (But you already knew that ...)
But why do we need this when we already can use new SomeClass().getClass() expression?
Because new SomeClass() creates a new instance of SomeClass():
This is unnecessary
It may be expensive
It may have unwanted side-effects
It may be necessary to supply multiple arguments
It may not even be possible; e.g. if the constructors are not accessible, or the class is abstract.
And when do we need to use this SomeClass.class expression in a statement?
There are numerous use-cases involving reflection where you need the Class object for a class to do things. Start by reading a good tutorial on Java reflection.
I am referring to Anonymous Inner classes
A class literal can't be used to get the Class of an anonymous inner class. But this.getClass() will work in any instance1 method of an anonymous class.
... it occurred to me we can't use the getClass() method in a static method.
Well, I guess that would be a scenario where you need a class literal.
But strictly speaking you can call getClass() in a static method. The problem is that you can't call it on this, either explicitly or implicitly.
1 - I can't think of a convincing use-case for a static method in an anonymous class. It would only be possible to refer to such a method outside of the anonymous class by using reflection. So it may as well be declared as an instance method.
This question already has answers here:
Why does every object in Java implicitly extend java.lang.Object class?
(11 answers)
Closed 8 years ago.
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object.
why do we need a class that is the super class of every other class in java ?
Because this is how Java is being designed. Java treats everything (except pirmitives) as an object including your self-defined objects.
There is an advantage by making all newly created classes to extend from Object. It allows common methods and attributes to be automatically available upon creation of a new object.
Some of the common methods are for example: toString() and equals()..etc
It's useful to have a common behavior/interface among all types for operations like comparison among other things.
It's also useful for when you want to make an array or other collection which contains or can contain different types.
Having Object as an implicit base class of all Java classes helps you write code that does not depend on the precise type, such as a collection, a class that produces string representations, and so on. See documentation of java.lang.Object for a list of methods what every class supports "out of the box".
This is by no means a required feature of all languages: there are other languages where there is no mandatory common subclass. Doing it this way was a choice of the language designers.
As we know, in Java, method name is not sufficient to distinguish different methods.
I think (may be wrong), to distinguish a method, it needs the following info:
(className, methodName, methodParameters)
Further,
how to identify a method more efficiently internally?
I heard of "method id". Does it mean there is a mapping between the above triple and an integer, so JVM use only method id after parsing?
If so, is it resided in symbol table?
Thanks!
It's a CONSTANT_NameAndType_info Structure pointing at a method descriptor.
It pretty much consists of the method name, the parameter types, and (somewhat surprisingly) the return type.
I do not understand very well what you are trying to do but I think there are some possible answers nonetheless:
You may be interested in the JNI Method Descriptors, one of the various string formats used internally by the JVM (and by JNI libraries) for identifying Java elements.
It is difficult to know about what you are talking about. The "method id" can be a reference for a java.lang.reflect.Method object, or can be the method descriptor mentioned below, or any other thing. Where did you read about it?
I doubt there is such table inside the JVM. I mean, I doubt there is a global table, because almost always you retrieve a method from a class, even when dealing with it inside the JVM, so it is reasonable to believe the method is stored in the class. It is likewhen we use reflection to retrieve a method:
Class clazz = String.class;
Method method = clazz.getDeclaredMethod("charAt", Integer.TYPE);
System.out.println(method.getName());
Note that I ask the class String for the method, instead of asking some util class to give me the method charAt, which receives an int and is from the class String.
In other words, your identification tuple is almost correct - it just does not have a class:
(methodName, methodParameters)
and, instead of retrieving the method from the JVM passing the class and then the method name and then the parameter types, you retrieve the method directly from the class, giving the class the method name and the parameter types. A subtle difference, for sure, but I think it is what you are wondering about.
This is evident even in the JNI descriptors I mentioned below. For example, the method
long f(int i, Class c);
is represented by the following descriptor:
"(ILjava/lang/Class;)J"
Note that there is no reference to the class of the method.
The excellent documentation on the class file format (already pointed by #Lawence) may give you some insights. I recommend you to read it fully.
1) How to identify a method more efficiently internally?
Internally to what? There are many places where a method might need to be "identified" "internally". In the bytecode compiler, the JIT compiler, the classloader / linker, the classfile representation, reflection API, a debugger and so on. They each have different efficiency concerns.
2) I heard of "method id". Does it mean there is a mapping between the above triple and an integer, so JVM use only method id after parsing?
A method id is used in the classfile representation, and could be used by anything based on that, including the class loader / linker, the JIT compiler and the debugger.
The JVM doesn't parse Java code.
3) If so, is it resided in symbol table?
It might do. It depends on what you mean by "the symbol table". Bear in mind that there are lots of places where method identification is required, throughout the lifecycle of a class. For instance, the Java reflection APIs require method information to implement methods such as getDeclaredMethod(...) and various methods of Method.
Java always differentiate its language elements by their fully qualified names.
Suppose you have a method myMethod(int a, int b) in class MyClass which lies in the package com.mypackage then java will identify the method with the name com.mypackage.MyClass.myMethod(int a , int b).
Just to give you some more insight, it also takes the Class Loader into consideration when there is a need to resolve two identical elements.
It does consider, which class loader was used to load the particular class containing the method to which you are referring. There are four types of class loaders in java. You can read the documention for java.lang.Thread class for this.
From the An Overview of the Scala Programming Language, Second Edition:
// Scala
object PrintOptions {
def main(args: Array[String]): Unit = {
System.out.println("Options selected:")
for (val arg <- args)
if (arg.startsWith("-"))
System.out.println(" " + arg.substring(1))
}
}
In the example above, the Scala program invokes methods startsWith
and substring of String, which is a class defined in Java. It
also accesses the static out field of the Java class System, and
invokes its (overloaded) println method. This is possible even
though Scala does not have a concept of static class members. In fact,
every Java class is seen in Scala as two entities, a class
containing all dynamic members and a singleton object, containing all
static members.
I understand translation of Scala's companion objects into Java bytecode, but I am not sure what exactly does it means bold text in upper blockquote "is seen in Scala" for opposite example (from Java to Scala).
Does it mean that Java classes with static members are actually converted or just interpreted as two entities in Scala? Or both of my assumptions are wrong?
I think you might be blinded by Java assumptions. Consider this simple snippet of code:
X.Y()
The means that the method Y is being called on the object X, or on some other object which X was implicitly converted into.
Maybe that doesn't look surprising, or you don't see anything amiss with that, so let's state explicitly a consequence: X will NEVER be a class. You don't invoke methods on classes, period.
Naturally, that presents a serious interoperability problem with Java regarding static members, and that's why it is stated that static members of a Java class X will be "seen" as a singleton object: because, otherwise, you'll never be able to use them.
Note that Scala's singleton objects are true objects -- they are instances of singleton classes. Java classes with static members will not give origin to single objects, though. In practice, this means that this line:
val x = X
will work if X is a Scala singleton object, but won't work if it is a Java class with static members.
It simply means that scala doesn't change anything to the initial java code, where static members and non-static members are in the same class.
Thus your second assumption is true, the first one is false.
I guess the book use seen instead of interpreted because this last one can have a different meaning if you think about "interpreted languages" (which are meaningless in that context).
I'm building a small Android application, but this is more of a Java question than an android question. Looking through the tutorials there are lines that look like:
startService(new Intent(this, MyService.class));
what exactly does the "MyService.class" field represent? Is that just a reference to the class for a template?
Thanks.
Andy's answer is definitely correct, but I want to expand on the point a little.
.class is a special syntax for obtaining an instance of a Class object. It can be used when only the type is available and no instance of the related object is around. It can be used with any concrete type name, including arrays and primitives. For instance, int.class is valid.
This way (and other ways) to get a Class object are documented in the old Sun reflection API docs.
The special .class syntax often appears in idiomatic usage as a "type token" in generic code. A class literal obtained with .class is called a type token when "passed among methods to communicate both compile-time and runtime type information" (Joshua Bloch's Effective Java 2e, p. 142).
Yes, MyService.class returns a Class object that represents the class MyService. The Intent uses it to identify which Service or Activity you're intending to start.
The MyService.class allows you to get the Class object describing the MyClass class, from the class name alone (as opposed to have an instance of the class to ask for object.getClass()).
In JVM, when a class is loaded, an object of the type Class represents the loaded class in memory. com.abc.MyClass.class is a literal expression that represents the Class object for the class com.abc.MyClass.
The same Class object can also be obtained by calling myClassReference.getClass() method if you have a reference to an object of the class.
The Class object can be used to find the information on the structure of the class, access fields, invoke methods and instantiate objects of the class using Java Reflection API.