I kind of new to java and will be happy if anybody could explain the following code samples to me.This is just a sample java code snippet for illustration. But the main question is that if the class Learn initializes another class Smart with a parameter which is also a class Object , then the addition of the dot class to the class Object Sample is kind of confusing to me. Any explanation will be appreciated. I apologize if it is a basic question. thanks.
class Learn {
//some codes
Smart smart = new Smart(Sample.class);
//some codes
}
Sample is the name of a class. It is not an object. A new Sample() is an object whose class is Sample. Sample.class is an object whose class is java.lang.Class which describes the class Sample.
In java, there is a class called "Class" that represent classes and interfaces.
There are several ways to get an instance of class "Class". Please take a look at java.lang.Class document.
Class.forName(String className)
obj.getClass() -obj is any class instance
Sample.class -Sample is a class
You are using the 3rd method to get an instance of class "Sample".
I will break your example in the following way....
Learn - is a Class
smart - is an Object Reference Variable of type Smart, we can say that Class Learn has a reference of type Smart.
Sample.class - Is a way of getting the Class<T> for a particular type.
Extract from Java Docs.
During implementation it depends on the Targeting bytecode version. If -target 1.4 (or below), a call to Class.forName() is inserted into your code in a static method which is called during type initialization. If you use -target 1.5 (or above) the constant pool gets a "class" entry
Please refer section 15.8.2 of the Java Language Specification for more details
Related
I am beginner in programming and i just started working with greenfoot (software for creating games using Java). When i was writing code i had to use construction builded in greenfoot which was using parameter described as: java.lang.class where i had to type ClassName.class . I was trying to go through documentation and a lot of other sources to figure out how it works and what is this, but to be honest i couldnt understand anything. Is there is someone who can tell me in simply words what does it mean and how construction like ClassName.class works? That is the first time i see dot notation used like this, before I have seen only dot notation when i tried to refer to for example other class method like: OtherClass.method() . So is it just builded in instance variable of every class or something like this? Thanks in advance
It's called a class literal. ClassName.class provides access to the instance of Class that represents the given class. So for instance, String.class refers to the Class instance for the String class. Using that object, you can do do various things (like find out what its members are at runtime via reflection). (FWIW, objects provide also access to the Class instance for their class via their getClass method.)
Assume I find something lacking in the default base class Object, and write a class of my own to use instead.
class MyObject extends Object
{
...
}
Is there a way to tell the Java compiler to use my new class as base class instead of the Object class?
Thus avoiding
class MyClass extends MyObject
and just go
class MyClass
and have it implicitly extend MyObject using, say a command line parameter to the compile
javac MyClass --defaultBase=MyObject
That would mean that all Jars and pre-compiled Class-files would use Object, but anything I compile myself would use my own class, except of course, my new base class. (I wouldn't want a circular dependency, would I.)
You can change the Object class within many limitations, but that not really a good idea. The best solution is to create your own class you want other classes to extend.
If you want to extend Object, the best option is to create a Utility method which takes an Object as an argument.
Is there a way to tell the Java compiler to use my new class as base class instead of the Object class?
No. You can't.
The Java Language Specification (JLS 4.3.2) states that the java.lang.Object class is a superclass of all other classes. If a compiler didn't implement that, it wouldn't be a compliant Java compiler. At any rate, I know of no Java compiler ("compliant" or not) that does allow you to do this.
#Peter Lawrey mentions that it is possible to change the Object class. This is true ... if you know what you are doing. But there are dependencies on internal details of the Object class hard-wired into other class ... and the native code implementation of the JVM. If you change some things (for example, adding instance fields or changing method signatures) you are liable to break the JVM, tools in the Java tool-chain, and/or 3rd-party libraries and tools (like your favourite IDE!). The breakage is liable to be castrophic, and difficult to diagnose.
On top of that, if your change doesn't break Java, you are still stuck with the problem that a real JVM won't run your code. That makes monkeying with Object a viable proposition for "research purposes only" ... at best.
For the record, it is technically possible to override the core classes of the the Java runtime library using the -Xbootclasspath VM option(s) (type java -X to get the info). However, this is not intended to be done by a usual developer (see other answers to this question).
You can try it yourself by modifying and compiling the source of the java.lang.Object to a directory named core-classes, for example, and passing the -Xbootclasspath/p:core-classes as a JVM argument.
I'm learning java reflection and I'm curious to know what use java.lang.reflect.Modifier has for a public constructor. The java documentation doesn't give any description or use for it and the class has only static methods and constants.
EDIT: Added some test code.
import java.lang.reflect.*;
public class TestModifier {
Modifier modifier = new Modifier(); // Compiles fine.
// Math math = new Math(); // Won't compile. Math() has private access.
}
The constructor exists and it's present in the javadoc although no info is present.
I found some information about it in the a source code comment in the GNU classpath, a project that is and I quote:
(GNU Classpath, Essential Libraries for Java,) is a GNU project to create free core class libraries for use with virtual machines and compilers for the java programming language.
In their source code for the Modifier class you can find the following non-javadoc comment for the constructor:
This constructor really shouldn't be here ... there are no instance methods or variables of this class, so instantiation is worthless. However, this function is in the 1.1 spec, so it is added for completeness.
I don't know if this is totally accurate since I could only access Java 1.3.1 spec and in the reflection model part of it what you can read is (bold's mine):
The Modifier class is an uninstantiable class that exports class methods to decode Java language modifiers for classes and members. The language modifiers are encoded in an integer, and use the encoding constants defined by The Java Virtual Machine Specification.
I do wanna believe in the comment from the source code, but I can't really point you at the specification where such thing is said.. Even stranger to me is that the previous quote even being from spec 1.3 already states that it's uninstantiable.
This is definitely not an error in javadoc. You can't find such a constructor means this is a default constructor (no arg constructor) which is by default public because the java.lang.reflect.Modifier is a public class.
It might be the property of javadoc if used with default options , that it provides default constructor in documentation if the Parameter-less constructor is not defined for that class and there is no other constructor with parameters.
Good find, this is an oversight of the API designer.
But, it also proves that it is not a big deal at all to instantiate a utility class; new Modifier() has never caused anybody any problem. Neither would new Math().
Don't listen to chicken little.
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'
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.