Java.class

In Java, given an object, an instance of a class, you can get the class name by coding the following:

Class clazz = obj.getClass();
String clazzName = clazz.getName();

Sometimes you want you want to create a Class object for a given class. In this case you can do so by writing code similar to the following example:

Class clazz = MyClass.class;

Many plugin frameworks, including the JDBC Driver Manager will create a Class object without having the knowledge of what class name at compile time. There might be a case where you know a class implements a given interface but you don’t know the class name of the implementation until at runtime when you read it from a properties file. In situations like this you can do the following:

String clazzName = "com.juixe.techknow.MyClass";
...
Class clazz = Class.forName(clazzName);

Sometimes you will need a Class object for a primitive type. You might need a Class object for an int or boolean when dealing with reflection. In this case you do so using the dot class notation on a primitive type. Here is a more elaborate example where we create a Class object for an int primitive:

int newValue = ...
Class clazz = obj.getClass();
Method meth = clazz.getMethod("setValue", new Class[]{int.class});
meth.invoke(obj, new Object[]{new Integer(newValue)});

You can also get the class for an array. The only place where I have ever need the class of an array is when working with reflection. Here is how you can get the class for an array:

Class clazz = String[].class;

Technorati Tags: , , ,

Related posts:

  1. Fix Common Java Exceptions
  2. How To Print The Alphabet in Java?
  3. Class HighLite GraphicsEnvironment
  4. Java String Conversion Puzzlers
  5. Class HighLite Calendar
  6. Jakarta BeanUtils PropertyUtils


Leave a Reply