Please note that I can't get forName() to work specifically with "int".
On the other hand, it works alright with a class I created in the same package as
Class.forName("mypackage.dummyclass")
Is that something to do with fully qualified names? I've tried "java.lang.int" and "java.lang.integer", but it didn't help.
int is a primitive type in Java, not a class, so try java.lang.Integer instead (which is not exactly the same thing but is interchangeable for many purposes)
The correct syntax for getting the Class object associated with primitive types, like int, is
int.class
Likewise, you use byte.class, long.class, boolean.class, etc. for the other primitive types.
While there's a special relationship between int and java.lang.Integer, int.class is not the same thing as Integer.class.
Note that you cannot use Class.forName with a primitive type name.
As documented in the Java tutorial:
Class.forName()
If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName(). This cannot be used for primitive types.
And from the same tutorial, on how to use the .class syntax with primitives:
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
Class.forName is for class objects but int is primitive data type.
Try java.lang.Integer instead.
int is a primitive data type, not a class. Integer class can be used for int. So you should use "Integer".
Instead of java.lang.integer, try java.lang.Integer (With Capital I)
The above will work because, Class.forName() tries to create an object of the full class name passed as String arg in it.
java.lang.Integer - This is a class
int - This is not a class. It is a primitive data type. Hence, failing.
Related
In java API documentation, it is written that Boolean wrapper class have 3 fields. True, False and Type.
For Type they have given description that:
TYPE: The Class object representing the primitive type boolean.
I can't understand what is this "type" field for?
Every Java class is represented in a running Java program by an object of type java.lang.Class, which, amongst other things, lets you perform reflective operations upon objects of that type. You can normally get to an object's Class by calling obj.getClass(), or by specifying its name explicitly, eg. String.class.
Primitive types, like int and boolean, don't have a class to represent them. But there are situations where it would be appropriate to have a Class object for them, and the TYPE members of the wrapper class types (like java.lang.Integer and java.lang.Double) represent exactly these Class objects.
You might be given one if you perform reflective operations on, say, an array of booleans, like this:
boolean[] bools = new boolean[1];
Class<?> c = bools.getClass().getComponentType();
Assert.assertEquals(Boolean.TYPE, c); // passes!
Note that the primitive boolean class is NOT the same as the Boolean wrapper class! That is,
Assert.assertNotSame(Boolean.TYPE, Boolean.class); // passes!
TYPE is a Class<Boolean> compile-time constant of the Boolean wrapper class representing the primitive type (boolean) the Boolean class wraps around.
The same is in all object wrappers: they all have a TYPE constant representing their primitive counterpart (e.g. Integer.TYPE).
It is used in the reflection API, to represent the type of a boolean argument or return type of a method, or the type of a field of a class.
I accidentally found that this works:
Class<?> a;
a = int.class;
System.out.println(a); // int
a = Integer.class;
System.out.println(a); // class java.lang.Integer
What does it really mean / do for primitives?
I tried and neither List<int> nor List<int.class> works (yeah, I know I have to use Integer). Also, obviously, I can't invoke getClass() on primitives, so it's useless for type checking of any sort.
In what situation would I use int.class and why is it even present in the language?
You would use it when you are trying to locate a method having an int argument via the reflection API.
From the specs:
The type of p.class, where p is the name of a primitive type
(§4.2), is Class<B>, where B is the type of an expression of
type p after boxing conversion (§5.1.7).
And
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.
So how about
Class<Integer> a = int.class;
When to use: Lots of reflection use cases (for instance in argparse4j they use it to map from command line parameters to methods).
I know that java is not supposed support generic arguments which are primitive types, and sure enough something like:
Vector<byte> test;
will fail to compile.
however with a little slight-of-hand that I accidentally performed in a program, I found that it is actually possible to create a generic object with a primitive type (technique shown below)
Furthermore, java falsely allows this instance to be assigned to a variable of type Vector<Byte> when as the print statements show, byte.class and Byte.class are two separate beasts. Because of this, attempts to do calls on the object result in unexpected and strange behaviors/errors.
Is this a java bug? or is there some rhyme or reason to this madness? It seems like even if java allowed the unexpected behavior of creating primitive-typed generics, they should not be assignable to a generic of the wrapper type which is of a distinct class from the primitive.
import java.util.Vector;
public class Test
{
//the trick here is that I am basing the return type of
//the vector off of the type that was given as the generic
//argument for the instance of the reflections type Class,
//however the the class given by byte.class yields a non-class
//type in the generic, and hence a Vector is created with a
//primitive type
public static <Type> Vector<Type> createTypedVector(Class<Type> type)
{
return new Vector<Type>(0,1);
}
public static void main(String ... args)
{
//these lines are to demonstrate that 'byte' and 'Byte'
//are 2 different class types
System.out.println(byte.class);
System.out.println(Byte.class);
//this is where I create an instance of type Vector<byte>
//and assign it to a variable of type Vector<Byte>
Vector<Byte> primitiveTypedGenericObject = createTypedVector(byte.class);
//this line causes unexpected exceptions to be thrown
//because primitiveTypedGenericObject is not actually type
//Vector<Byte>, but rather Vector<byte>
primitiveTypedGenericObject.set(0,(byte)0xFF);
}
}
Both Byte.class and Byte.TYPE are Class<Byte> objects. The latter are just used to distinguish between primitive type and object type.
Actually Byte.TYPE is defined as:
public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
and getPrimitiveClass is an opaque method which retrieves the type from the VM so we can't investigate it further.
So, even if you think that you are passing a primitive data type Class, since they don't exist (why should they, since they refer to something that is typable according to the Java typing system for objects, which doesn't include primitive types until they are boxed into wrapper classes), you are creating a Vector<Byte>.
But in the end this doesn't matter much, upon reaching run-time execution type annotations are erased and the generic type doesn't mean anything. Whenever you'll add a byte it will be autoboxed to a Byte object and that's it.
I have no way to test your code at the moment, which exceptions are thrown at runtime when adding items to the Vector?
You've stumbled upon autoboxing and unboxing. See http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
The nutshell version
List<Integer> list = new List<Integer>();
list.add(1); // works
byte.class, int.class, etc. resolve to Byte, Integer, etc. See the Java Language Specification, 15.8.2:
15.8.2. Class Literals
......
The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).
The type of void.class (§8.4.5) is Class<Void>.
No! It is not bug. It is called Autoboxing. When you pass byte to a generic method that expects Byte, the compiler automatically Autoboxes it to Byte which is an instance of Object. The antithesis of that operation is called Auto Unboxing and that is why operations like the one shown below are legal.
int a = new Integer(5);
Integer b = 5;
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.
I have read that in order to access the call object representing a primitive type, I can do this:
Class intClass = int.class;
But how do primitive types have classes to represent them? They are primitive, which should mean they have no class. Why does the example above work, and what class contains int (Integer class maybe)?
As the javadoc for the Class class states
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.
A Class object simply provides some metadata and factory methods for the type it represents.
For example, Class#isPrimitive() will tell you if the represented type is a primitive.
The class Class and its instances are, among other things, used for reflection.
Let's say you had the a class like
public class Example {
public long add(int first, long second) { // for whatever reason
return first + second;
}
}
and you wanted to invoke the add method, given only its name and parameter types. The following would fail
Class<?> exampleClass = Example.class;
exampleClass.getMethod("add", Integer.class, Long.class);
because the parameter types are not Integer and Long, they are int and long.
You'd have to do something like
Class<Example> exampleClass = Example.class;
Method addMethod = exampleClass.getMethod("add", int.class, long.class);
Example instance = exampleClass.newInstance();
addMethod.invoke(instance, 42, 58L);
If you look at the field summary for the Integer class, you will find that the primitive type int is actually represented by the class instance TYPE. Therefore, int.class would equal Integer.TYPE.
Here's a link to Javadocs where you can find the TYPE class instance.
When you type int.class you get the corresponding object wrapper class, which every primitive has. Read the Java tutorials on autoboxing for more information, and to see each primitive's corresponding wrapper class.