黑马程序员-Reflect(1)

来源:互联网 发布:安卓时间网络同步不 编辑:程序博客网 时间:2024/06/11 22:07

---------------------android培训、java培训、期待与您交流! -------------------------

获取Class Object:

Object.getClass()

  • 从Object继承
  • 引用类型对象,存在对象的实例
  • 不可以用来操作原始类型

示例代码如下:

//获取String对象的Class ObjectClass<?> c = "uc".getClass();System.out.println(c.getName());//输出:java.lang.Stringenum E { A, B };System.out.println(E.A.getClass().getName());//输出:com.uc.reflecttest.Ebyte[] bytes = new byte[1024];System.out.println(bytes.getClass().getName());//输出[BMap<string string=""> map = new HashMap<string string="">();System.out.println(map.getClass().getName());//输出 java.util.HashMap//Note: 输出的不在Map接口类型, 页是map引用对象的实际类型int ival;Class ci = ival.getClass();//编译时错误</string>

The .class Syntax

  • 获取原始数据类型的Class Object
  • 在不存在对象实例的情况下,可以用类的名称加".class"来获取Class Object
Class c = int.class;System.out.println(c.getName());//输出: intSystem.out.println(int[].class.getName());System.out.println(int[][].class.getName());System.out.println(int[][][].class.getName());/*输出:[I[[I[[[I*/

Class.forName()

  • 不可以用来操作原始类型
  • 需要提供完整的类名称
Class c = Class.forName("java.util.Date");System.out.println(c.getName());//Output: java.util.DateClass cDoubleArray = Class.forName("[D");System.out.println(cDoubleArray.isArray());//output:trueSystem.out.println(cDoubleArray.getComponentType().getName());//output:double

TYPE Field for Primitive Type Wrappers.

System.out.println(Double.TYPE == double.class);//output: trueSystem.out.println(Integer.TYPE == int.class);//output: true

查看类的修饰符和继承类型:

一个类的申明中,可以包含一个或多个影响它的 Runtime behavior 的修饰符。常见的修饰符如下:

  • Access modifiers: public, protected, private
  • Modifier requiring override: abstract
  • Modifier restricting to one instance: static
  • Modifier prohibiting value modification: final
  • Modifier forcing strict floating point behavior: strictfp
  • Annotations

与修饰符相关的操作类:java.lang.reflect.Modifier

intgetModifiers()
Returns the Java language modifiers for this class or interface, encoded in an integer.
TypeVariable<Class<T>>[]getTypeParameters()
Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclarationobject, in declaration order
Type[]getGenericInterfaces()
Returns the Types representing the interfaces directly implemented by the class or interface represented by this object
Annotation[]getAnnotations()
Returns annotations that are present on this element.

以下为Java tutorial 中的一段示例代码:

import java.lang.annotation.Annotation;import java.lang.reflect.Modifier;import java.lang.reflect.Type;import java.lang.reflect.TypeVariable;import java.util.Arrays;import java.util.ArrayList;import java.util.List;import static java.lang.System.out;public class ClassDeclarationSpy {    public static void main(String... args) {try {    Class<?> c = Class.forName(args[0]);    out.format("Class:%n  %s%n%n", c.getCanonicalName());    out.format("Modifiers:%n  %s%n%n",       Modifier.toString(c.getModifiers()));    out.format("Type Parameters:%n");    TypeVariable[] tv = c.getTypeParameters();    if (tv.length != 0) {out.format("  ");for (TypeVariable t : tv)    out.format("%s ", t.getName());out.format("%n%n");    } else {out.format("  -- No Type Parameters --%n%n");    }    out.format("Implemented Interfaces:%n");    Type[] intfs = c.getGenericInterfaces();    if (intfs.length != 0) {for (Type intf : intfs)    out.format("  %s%n", intf.toString());out.format("%n");    } else {out.format("  -- No Implemented Interfaces --%n%n");    }    out.format("Inheritance Path:%n");    List<class> l = new ArrayList<class>();    printAncestor(c, l);    if (l.size() != 0) {for (Class<?> cl : l)    out.format("  %s%n", cl.getCanonicalName());out.format("%n");    } else {out.format("  -- No Super Classes --%n%n");    }    out.format("Annotations:%n");    Annotation[] ann = c.getAnnotations();    if (ann.length != 0) {for (Annotation a : ann)    out.format("  %s%n", a.toString());out.format("%n");    } else {out.format("  -- No Annotations --%n%n");    }        // production code should handle this exception more gracefully} catch (ClassNotFoundException x) {    x.printStackTrace();}    }    private static void printAncestor(Class<?> c, List<class> l) {Class<?> ancestor = c.getSuperclass(); if (ancestor != null) {    l.add(ancestor);    printAncestor(ancestor, l); }    }}

查看类的成员:

对象的成员

类的成员:Field, Method, Constructor

获取具体的一个成员:
get{[Field|Method|Constructor]}
getDeclared{[Field|Method|Constructor]}

获取某种类型成员的集合:
get{[Fields|Methods|Constructors]}
getDeclaredt{[Fields|Methods|Constructors]}

import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Member;import static java.lang.System.out;enum ClassMember { CONSTRUCTOR, FIELD, METHOD, CLASS, ALL }public class ClassSpy {    public static void main(String... args) {try {    Class<?> c = Class.forName(args[0]);    out.format("Class:%n  %s%n%n", c.getCanonicalName());    Package p = c.getPackage();    out.format("Package:%n  %s%n%n",       (p != null ? p.getName() : "-- No Package --"));    for (int i = 1; i < args.length; i++) {switch (ClassMember.valueOf(args[i])) {case CONSTRUCTOR:    printMembers(c.getConstructors(), "Constructor");    break;case FIELD:    printMembers(c.getFields(), "Fields");    break;case METHOD:    printMembers(c.getMethods(), "Methods");    break;case CLASS:    printClasses(c);    break;case ALL:    printMembers(c.getConstructors(), "Constuctors");    printMembers(c.getFields(), "Fields");    printMembers(c.getMethods(), "Methods");    printClasses(c);    break;default:    assert false;}    }        // production code should handle these exceptions more gracefully} catch (ClassNotFoundException x) {    x.printStackTrace();}    }    private static void printMembers(Member[] mbrs, String s) {out.format("%s:%n", s);for (Member mbr : mbrs) {    if (mbr instanceof Field)out.format("  %s%n", ((Field)mbr).toGenericString());    else if (mbr instanceof Constructor)out.format("  %s%n", ((Constructor)mbr).toGenericString());    else if (mbr instanceof Method)out.format("  %s%n", ((Method)mbr).toGenericString());}if (mbrs.length == 0)    out.format("  -- No %s --%n", s);out.format("%n");    }    private static void printClasses(Class<?> c) {out.format("Classes:%n");Class<?>[] clss = c.getClasses();for (Class<?> cls : clss)    out.format("  %s%n", cls.getCanonicalName());if (clss.length == 0)    out.format("  -- No member interfaces, classes, or enums --%n");out.format("%n");    }}             

---------------------android培训、java培训、期待与您交流! -------------------------

0 0