开发者

What is a class literal in Java?

From the Java tutorial:

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.

To what type of variable can this literal be assigned to?

Please give a small example if possible.


Class<String> c = String.class;

Check out the Javadoc for java.lang.Class to see what you can do with one of these little guys - mostly related to reflection


To understand that, you have to understand that String is an instance (object) of the class Class. A string literal (e.g. "I am a string.") is a notation which represents an instance (object) of the class String, whereas a class literal (e.g. Hashtable.class) is a notation which represents an instance of the class Class.


Thanks to the other good answers here, you know what it is, but here's a typical usage example that may clarify also:

    private static Logger log = Logger.getLogger(YourClassHere.class);

As the code suggests, this is a line where we're initialising a logging framework (in this example, I'm using the org.apache.log4j package, but the principle extends to other frameworks). The getLogger() method requires a class literal so it knows what it's logging (i.e. the current object's class).


According to the Java Language Specification (JLS):

15.8.2 Class Literals

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.


Some common uses may be found in Class Literals as Runtime-Type Tokens. The approach is widely used to implement the observer pattern, as seen in the EventListenerList, discussed here. The Converter application includes an example in ConverterRangeModel.


The literal itself is MyClass. If you write MyClass.class you get a Reference to the class object. If you write new MyClass(), it uses the literal to get you an instance of the class object you get by MyClass.class. From the instance you get the same class object by calling myClassInstance.getClass().

I am not 100% sure, but the literal itself cannot be assigned to any variable. What you can do is getting the name of the class as string and use the reflection framework to create an instance.


In examples it is someting like that:

Class myClass = MyClass.class

or

MyClass.class.getResourceAsStream("config.properties");


To understand that, you have to understand that String is an instance (object) of its superclass (parent class) Object.

class String's instance (object)'s value is a String literal (e.g. "I am a string.") :

class   |  instance (object) |  literal
------------------------------------------------
String  |  instance_name  =  |  "I am a string."

whereas class Object's instance (object)'s value is a Class literal — (e.g. Hashtable.class) which refers to class Hashtable's instance (object)

class      |  instance (object) |  literal
------------------------------------------------
Hashtable  |  instance_name     |  Hashtable.


When the JVM loads your application classes, it stores them as java.class.Class objects.

So, there are usually several instances of type Class in memory that represents your classes. So you can do something like this:

Class<Bicycle> bicycleClass = Bicycle.class; // returns the object storing your Bicycle class
bicycleClass.getName();  // returns your class name
bicycleClass.getDeclaredMethods();  // returns your (declared) class methods


package training;

import java.lang.reflect.Method;

public class Training {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Class<Training> myclass = Training.class;
        Method[] myclassarr = myclass.getDeclaredMethods();
        System.out.println(myclass);
        System.out.println(myclass.getName());
        for (int i = 0; i < myclassarr.length; i++) {
            System.out.println(myclassarr[i]);
        }
        System.out.println();
        Class<String> strobj = String.class;
        System.out.println(strobj);
        System.out.println(strobj.getName());
        Method[] strobjarr = strobj.getDeclaredMethods();
        for (int j = 0; j < strobjarr.length; j++) {
            System.out.println(strobjarr[j]);
        }
    }

    public void MethodA() {

    }

    public static void MethodB() {

    }
}

Output:

class training.Training
training.Training
public static void training.Training.main(java.lang.String[])
public void training.Training.MethodA()
public static void training.Training.MethodB()

class java.lang.String
java.lang.String
public boolean java.lang.String.equals(java.lang.Object)
public java.lang.String java.lang.String.toString()
public int java.lang.String.hashCode()
public int java.lang.String.compareTo(java.lang.String)
public int java.lang.String.compareTo(java.lang.Object)
public int java.lang.String.indexOf(java.lang.String,int)
public int java.lang.String.indexOf(java.lang.String)
public int java.lang.String.indexOf(int,int)
public int java.lang.String.indexOf(int)
static int java.lang.String.indexOf(char[],int,int,char[],int,int,int)
static int java.lang.String.indexOf(char[],int,int,java.lang.String,int)
public static java.lang.String java.lang.String.valueOf(int)
public static java.lang.String java.lang.String.valueOf(long)
public static java.lang.String java.lang.String.valueOf(float)
public static java.lang.String java.lang.String.valueOf(boolean)
public static java.lang.String java.lang.String.valueOf(char[])
public static java.lang.String java.lang.String.valueOf(char[],int,int)
public static java.lang.String java.lang.String.valueOf(java.lang.Object)
public static java.lang.String java.lang.String.valueOf(char)
public static java.lang.String java.lang.String.valueOf(double)
public char java.lang.String.charAt(int)
private static void java.lang.String.checkBounds(byte[],int,int)
public int java.lang.String.codePointAt(int)
public int java.lang.String.codePointBefore(int)
public int java.lang.String.codePointCount(int,int)
public int java.lang.String.compareToIgnoreCase(java.lang.String)
public java.lang.String java.lang.String.concat(java.lang.String)
public boolean java.lang.String.contains(java.lang.CharSequence)
public boolean java.lang.String.contentEquals(java.lang.CharSequence)
public boolean java.lang.String.contentEquals(java.lang.StringBuffer)
public static java.lang.String java.lang.String.copyValueOf(char[])
public static java.lang.String java.lang.String.copyValueOf(char[],int,int)
public boolean java.lang.String.endsWith(java.lang.String)
public boolean java.lang.String.equalsIgnoreCase(java.lang.String)
public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[])
public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object[])
public void java.lang.String.getBytes(int,int,byte[],int)
public byte[] java.lang.String.getBytes(java.nio.charset.Charset)
public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException
public byte[] java.lang.String.getBytes()
public void java.lang.String.getChars(int,int,char[],int)
void java.lang.String.getChars(char[],int)
private int java.lang.String.indexOfSupplementary(int,int)
public native java.lang.String java.lang.String.intern()
public boolean java.lang.String.isEmpty()
public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.CharSequence[])
public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.Iterable)
public int java.lang.String.lastIndexOf(int)
public int java.lang.String.lastIndexOf(java.lang.String)
static int java.lang.String.lastIndexOf(char[],int,int,java.lang.String,int)
public int java.lang.String.lastIndexOf(java.lang.String,int)
public int java.lang.String.lastIndexOf(int,int)
static int java.lang.String.lastIndexOf(char[],int,int,char[],int,int,int)
private int java.lang.String.lastIndexOfSupplementary(int,int)
public int java.lang.String.length()
public boolean java.lang.String.matches(java.lang.String)
private boolean java.lang.String.nonSyncContentEquals(java.lang.AbstractStringBuilder)
public int java.lang.String.offsetByCodePoints(int,int)
public boolean java.lang.String.regionMatches(int,java.lang.String,int,int)
public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int)
public java.lang.String java.lang.String.replace(char,char)
public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence)
public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String)
public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)
public java.lang.String[] java.lang.String.split(java.lang.String)
public java.lang.String[] java.lang.String.split(java.lang.String,int)
public boolean java.lang.String.startsWith(java.lang.String,int)
public boolean java.lang.String.startsWith(java.lang.String)
public java.lang.CharSequence java.lang.String.subSequence(int,int)
public java.lang.String java.lang.String.substring(int)
public java.lang.String java.lang.String.substring(int,int)
public char[] java.lang.String.toCharArray()
public java.lang.String java.lang.String.toLowerCase(java.util.Locale)
public java.lang.String java.lang.String.toLowerCase()
public java.lang.String java.lang.String.toUpperCase()
public java.lang.String java.lang.String.toUpperCase(java.util.Locale)
public java.lang.String java.lang.String.trim()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜