`

class literal & instance.getClass() & Class.forName(String className)

阅读更多
常用的几种取得Class类实例的方式:
1 class literal (class字面量, 如String.class/int.class/void.class)
2 instanceOfClass.getClass();
3 Class.forName(String className)
4 classLoaderInstance.loadClass(String name, boolean resolve)

3 4 为显式的动态加载,关于动态加载,我要记得看附件中的Understanding Class.forName.pdf!关于ClassLoader的更多知识参阅 http://wuaner.iteye.com/admin/blogs/1011036,这里不再详述。


class literal:
Java Language Specification -> 15.8.2 Class Literals :
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2
引用
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type (§4.3), is Class<C>.
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>.



class字面量只能作用在type名上(这里的type包括class, interface, array, primitive type,void)!Object的方法getClass()作用在类实例上!它们返回的都是Class类的实例!
对一个Class类的实例clazz,可以一直调用getClass方法!而.class因为不能作用在类实例上,所以不能一直调下去,因为第一次调SomeClass.class时,返回的就已经是个Class类的实例了!


JDK中关于Class类:
引用
public final class Class<T>
extends Object
implements Serializable, GenericDeclaration, Type, AnnotatedElement

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.

The following example uses a Class object to print the class name of an object:

         void printClassName(Object obj) {
             System.out.println("The class of " + obj +
                                " is " + obj.getClass().getName());
         }
    

It is also possible to get the Class object for a named type (or for void) using a class literal (JLS Section 15.8.2). For example:

         System.out.println("The name of class Foo is: "+Foo.class.getName());
    

关于Class.forName():
引用
public static Class<?> forName(String name,
                               boolean initialize,
                               ClassLoader loader)
                        throws ClassNotFoundException

    Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName) this method attempts to locate, load, and link the class or interface. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.

    If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is name. Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void.

    If name denotes an array class, the component type of the array class is loaded but not initialized.

    For example, in an instance method the expression:

          Class.forName("Foo")
        

    is equivalent to:

          Class.forName("Foo", true, this.getClass().getClassLoader())
        

    Note that this method throws errors related to loading, linking or initializing as specified in Sections 12.2, 12.3 and 12.4 of The Java Language Specification. Note that this method does not check whether the requested class is accessible to its caller.

    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader.

    Parameters:
        name - fully qualified name of the desired class
        initialize - whether the class must be initialized
        loader - class loader from which the class must be loaded
    Returns:
        class object representing the desired class

使用clazz(a instance of Class).newInstance()时要注意:
引用
if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason,将会抛出InstantiationException



关于Object的getClass() 方法:
引用
public final Class<?> getClass()

    Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

    The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

    Number n = 0;
    Class<? extends Number> c = n.getClass();

    Returns:
        The Class object that represents the runtime class of this object.



What is a class literal in Java ?
http://stackoverflow.com/questions/2160788/what-is-a-class-literal-in-java
Understanding Class.forName()(请见附件pdf文档):
http://www.theserverside.com/news/1365412/Understanding-ClassforName-Java



例子:
public class Parent {

    public static void main(String[] args) throws Exception {
        
        
        Class c1 = void.class;
        Class c2 = int.class;
        Class c3 = Integer.class;
        System.out.println(c2 == c3); //false
        //Integer i = (Integer)c3.newInstance(); //会报InstantiationException,原因是Integer没有无参构造方法
        
        Class clazz1 = String.class;
        String string = (String)clazz1.newInstance();
        string = "ooo";
        System.out.println(string);
        Class clazz2 = Class.class;
        ///Class clazz3 = Class.forName("package.MyClass"); //必须处理ClassNotFoundException
        
        String str = "abc";
        Class clazz4 = str.getClass();
        
        Class clazz5 = clazz1.getClass().getClass().getClass();
        //Class clazz6 = String.class.class; //编译错误
        
        Class clazz7 = System.out.getClass().getClass();
        //Class clazz8 = System.out.class; //编译错误
        
        System.out.println(String.class == "abc".getClass()); //true
        System.out.println(Class.class == clazz1.getClass()); //true
        System.out.println(Class.class == clazz4.getClass()); //true
        System.out.println(String.class == "abc".getClass().getClass()); //false
        System.out.println(Class.class == clazz7.getClass().getClass()); //true
        
        Parent p = new Parent();
        System.out.println(p.getClass() == Parent.class); //true
        System.out.println(p.getClass().getClass() == Parent.class); //false
        
        Parent p2 = new Child();
        System.out.println(p2.getClass() == Parent.class); //false
        System.out.println(p2.getClass() == Child.class); //true
        System.out.println(p2.getClass().getClass() == Child.class); //false
        
        //System.out.println(String.class == Parent.class); //编译错误:Incompatible operand types  Class<String> and Class<Parent>
        System.out.println("abc".getClass() == p.getClass()); //false
    }

}

class Child extends Parent {
    
}



http://juixe.com/techknow/index.php/2006/05/08/javaclass/
引用
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;

分享到:
评论

相关推荐

    001-glib-gdate-suppress-string-format-literal-warning.patch

    001-glib-gdate-suppress-string-format-literal-warning.patch 001-glib-gdate-suppress-string-format-literal-warning.patch 001-glib-gdate-suppress-string-format-literal-warning.patch

    java中的Class类和反射.docx

    - **`public static Class&lt;?&gt; forName(String className)`**:这是一个原生方法,用于动态加载类。这个方法非常关键,比如在SQL中动态加载数据库驱动时会用到:`Class.forName("com.mysql.jdbc.Driver")`。 - **`...

    Python库 | ae_literal-0.2.31.tar.gz

    "Python库 | ae_literal-0.2.31.tar.gz" 是一个针对Python开发者的资源,主要用于后端开发。这个压缩包包含的是Python的一个库,名为ae_literal,版本号为0.2.31。在Python的世界里,库是开发者常用的工具,它们提供...

    06 You Don't Know JS:ES6 & Beyond.pdf

    - 介绍ES6中新增的字符串方法,如`String.includes()`、`String.startsWith()`等。 - 分析这些新方法如何简化字符串处理。 ##### 第七章:Meta Programming 元编程 1. **Function Names 函数名称** - 讨论如何...

    object-literal-gc.rar_objects

    在JavaScript编程语言中,"对象字面量"(Object Literal)是一种创建对象的简洁方式,类似于其他编程语言中的字典或映射结构。这个压缩包文件`object-literal-gc.rar_objects`及其包含的文件,如`7.3-10.js`、`7.3-...

    literal:用于处理文字JavaScript实用程序库

    if ( literal ( school ) . check ( "student.name.first" ) ) { // welcome first } 这消除了很多混乱的代码。 让我们考虑另一个例子。 而不是写: if ( literal ( school ) . check ( "student.name.first...

    org.apache.commons.lang jar包下载(commons-lang3-3.1.jar)

    org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org....

    org.apache.commons.lang jar包下载

    org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org....

    commons-lang.jar

    org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org....

    template-literal-源码.rar

    在JavaScript的世界里,模板字面量(Template Literal)是一种非常重要的语法特性,它极大地提升了我们编写字符串的能力。模板字面量的源码分析可以帮助我们深入理解这一特性背后的实现原理,从而更好地利用它来提高...

    blogstones:一个带有keystonejs和Next.js的博客网站

    如果您没有脚手架,请# To add MONGO_URIkubectl create secret generic blogstone-mongo-uri --from-literal=MONGO_BLOGSTONE_URI= ' your mongo uri to connect '用法skaffold dev # to orchestrate this app# ...

    Google C++ International Standard.pdf

    6.4 Name lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 6.5 Program and linkage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

    java-Generic-tools.rar_stringtools java

    String, String&gt;} 的对象,可以通过下面的方式实现: * {@literal Map&lt;String, String&gt; map = GenericUtils.getMap() }。但是不能直接作为参数使用,例如有这样一个方法: * {@literal setInfo(Map&lt;...

    C++11 & C++14 & C++17.rar

    5. **范围基础的for循环(Range-based for loop)**:简化遍历容器或数组的代码,如`for (auto& elem : container) { ... }` 6. **nullptr**:为零指针引入了一个新的类型`nullptr`,避免了整型零和空指针的混淆。 ...

    SystemVerilog Reference Manual 3.1a(中英文版)+最新SV IEEE 标准

    3.12 Class...............................................................................................................................................26 3.13 Singular and aggregate types .............

    Python EOL while scanning string literal问题解决方法

    在Python开发过程中,遇到错误提示“EOL while scanning string literal”时,通常意味着在解析字符串字面量时遇到了问题。具体来说,是在解析过程中遇到了行结束符(End Of Line),但字符串还没有被正确地闭合,...

    python3.6.5参考手册 chm

    PEP 3155: Qualified name for classes and functions PEP 412: Key-Sharing Dictionary PEP 362: Function Signature Object PEP 421: Adding sys.implementation SimpleNamespace Using importlib as the ...

    spring-framework-reference4.1.4

    Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ...........................................................................................

Global site tag (gtag.js) - Google Analytics