java 反射1 Class
来源:互联网 发布:音视频转换器mac 编辑:程序博客网 时间:2024/06/06 17:10
Java 反射API提供了一个简单的,类型安全的api用来支持类和对象的内省。api可以用来:
- 构建新的类实例和数组。
- 访问和修改对象和类的域。
- 调用对象和类的方法。
- 访问和修改数组的元素。
反射api定义了类和方法:
- 三个类-Field,Method,Constructor。
- Class类,提供构造一个Field,Method,Constructor类的实例。
- Array类,提供方法动太态构建和访问Java arrays。
- Modifier类,包含了所有修饰符的声明,包含了方法用来解码修饰符。
- InvocationTargetException类,包装了exceptions,被反射方法和构造器抛出。
- AccessibleObject 和 ReflectPermission类,提供一个机制来抑制标准Java访问权限。
java.lang包下的一些部分也支持反射:
- Static fields that hold instances of the class
Class
. These represent the primitive Java typesboolean
,byte
,char
,short
,int
,long
,float
, anddouble
, and the keywordvoid
, at run-time. - An uninstantiable placeholder class-
Void
-to hold a reference to theClass
object representing the keywordvoid
.
由于反射操作是动态解决的,当前的java虚拟机还无法执行优化。因此,反射操作比非反射要慢,应当避免频繁的使用。
java.lang.Class是所有反射api的入口。java.lang.reflect包中的所有类都没有公有的构造器。获取这些类,有必要调用Class类的适当的方法。
Object.getClass()
import java.util.HashSet;import java.util.Set;Set<String> s = new HashSet<String>();Class c = s.getClass();byte[] bytes = new byte[1024];Class c = bytes.getClass();enum E { A, B }Class c = A.getClass();Class c = System.console().getClass();
Class c = "foo".getClass();
The .class Syntax
boolean b;Class c = b.getClass(); // compile-time errorClass c = boolean.class; // correct
Class c = java.io.PrintStream.class;
Class c = int[][][].class;
Class.forName()
Class c = Class.forName("com.duke.MyLocaleServiceProvider");
Class cDoubleArray = Class.forName("[D");same asdouble[].class
Class cStringArray = Class.forName("[[Ljava.lang.String;"); identical toString[][].class
TYPE Field for Primitive Type Wrappers
Class c = Double.TYPE;
每个包装类能获取一个TYPE域,和原始类型的class一样。Class c = Void.TYPE;
Returns the super class for the given class.
Class.getSuperclass()
Class c = javax.swing.JButton.class.getSuperclass();
- Returns all the public classes, interfaces, and enums that are members of the class including inherited members.
Class.getClasses()
Class<?>[] c = Character.class.getClasses();
- Returns all of the classes interfaces, and enums that are explicitly declared in this class.
Class.getDeclaredClasses()
Class<?>[] c = Character.class.getDeclaredClasses();
- Returns the
Class
in which these members were declared.
Class.getDeclaringClass()
java.lang.reflect.Field.getDeclaringClass()
java.lang.reflect.Method.getDeclaringClass()
java.lang.reflect.Constructor.getDeclaringClass()
- Returns the immediately enclosing class of the class.
Class.getEnclosingClass()
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); } }}运行
java ClassDeclarationSpy java.util.concurrent.ConcurrentNavigableMap
Class: java.util.concurrent.ConcurrentNavigableMapModifiers: public abstract interfaceType Parameters: K V Implemented Interfaces: java.util.concurrent.ConcurrentMap<K, V> java.util.NavigableMap<K, V>Inheritance Path: -- No Super Classes --Annotations: -- No Annotations --
Class
APIgetDeclaredField()
nonoyesgetField()
noyesnogetDeclaredFields()
yesnoyesgetFields()
yesyesnoClass
APIgetDeclaredMethod()
nonoyesgetMethod()
noyesnogetDeclaredMethods()
yesnoyesgetMethods()
yesyesnoClass
APIgetDeclaredConstructor()
noN/A1yesgetConstructor()
noN/A1nogetDeclaredConstructors()
yesN/A1yesgetConstructors()
yesN/A1no一个官方的例子
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"); }}
$ java ClassSpy java.lang.ClassCastException CONSTRUCTORClass: java.lang.ClassCastExceptionPackage: java.langConstructor: public java.lang.ClassCastException() public java.lang.ClassCastException(java.lang.String)
0 0
- java 反射1 Class
- java 反射 class
- Java 反射类--Class
- java 反射 Class
- java反射:class类
- 反射1——Class类与Java反射
- 15. JAVA 反射机制 Part 1(Class类、反射、反射机制) ----- 学习笔记
- JAVA反射和CLASS类
- Java反射机制和Class
- Java反射机制-class类
- java反射机制---Class.forName("")
- Java反射机制--Class类
- Java反射之Class类
- Java反射(一)Class
- Java 反射之Class用法
- Class与java反射机制
- java反射 之Class类
- Class类与JAVA反射
- 二分匹配模板()
- oracle 使用ANY运算符
- 6.图文回复(微信公众号开发实战)
- 从0打造自己的mvc框架3-5 -3-6
- 智能物联网系统设计与实现
- java 反射1 Class
- 五边形数定理的一种证明
- Q-Learning算法分析与代码实现
- java2实用教程第四-五章读后感
- ajax - 服务器响应
- 【JZOJ4809】【NOIP2016提高A组五校联考1】挖金矿
- C#控制台基础 int类型的list中removeall用法示例
- Toolbar+RecyclerView进阶使用(仿淘宝列表、网格布局之间的切换)
- 商城之下拉刷新SwipeRefreshLayout控件介绍