java中反射问题
1.在java中反射的概念
2.反射是怎么实现的
3.应该在什么时候用
4.有什么好处
------解决方案--------------------http://www.newasp.net/tech/java/14890.html
------解决方案--------------------java的反射技术功能十分强大,整理一些资料!!
(如需转载,请注明出处!)
Lesson: 检测类examing class
1.Retrieving Class Objects
获取一个Class对象(metadata)
a,从对象的实例获取。
Class c = mystery.getClass();//(return Class)
b,从子类的实例获取
TextField t = new TextField();
Class c = t.getClass();
Class s = c.getSuperclass();
c,知道类名,则可以把.class加入到名字之后来获取。
Class c = java.awt.Button.class;
d,如果类名在编译时是未知的,则可以使用Class.forName()方法来获取.
Class c = Class.forName(classString);
2.Getting the Class Name
获取类名称
c.getName();
例如:
import java.lang.reflect.*;
import java.awt.*;
class SampleName {
public static void main(String[] args) {
Button b = new Button();
printName(b);
}
static void printName(Object o) {
Class c = o.getClass();
String s = c.getName();
System.out.println(s);
}
}
3.Discovering Class Modifiers
检索修改符
a.通过getModifiers()方法获取一个整型标识值。
b.通过java.reflect.Modifier对象的isPublic, isAbstract, 和 isFinal方法判断此值.
例如:
import java.lang.reflect.*;
import java.awt.*;
class SampleModifier {
public static void main(String[] args) {
String s = new String();
printModifiers(s);
}
public static void printModifiers(Object o) {
Class c = o.getClass();
int m = c.getModifiers();
if (Modifier.isPublic(m))
System.out.println( "public ");
if (Modifier.isAbstract(m))
System.out.println( "abstract ");
if (Modifier.isFinal(m))
System.out.println( "final ");
}
}
4.Finding Superclasses
检索父类
例如:
import java.lang.reflect.*;
import java.awt.*;
class SampleSuper {
public static void main(String[] args) {
Button b = new Button();
printSuperclasses(b);
}
static void printSuperclasses(Object o) {
Class subclass = o.getClass();
Class superclass = subclass.getSuperclass();
while (superclass != null) {
String className = superclass.getName();
System.out.println(className);
subclass = superclass;
superclass = subclass.getSuperclass();
}
}
}
5.Identifying the Interfaces Implemented by a Class
检索指定类实现的接口
例如:
import java.lang.reflect.*;
import java.io.*;
class SampleInterface {
public static void main(String[] args) {
try {
RandomAccessFile r = new RandomAccessFile( "myfile ", "r ");
printInterfaceNames(r);
} catch (
IOException e) {
System.out.println(e);
}
}
static void printInterfaceNames(Object o) {
Class c = o.getClass();
Class[] theInterfaces = c.getInterfaces();
for (int i = 0; i < theInterfaces.length; i++) {
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
}
6.Examining Interfaces
判定一个类是不是接口
import java.lang.reflect.*;
import java.util.*;
class SampleCheckInterface {
public static void main(String[] args) {
Class thread = Thread.class;
Class runnable = Runnable.class;
verifyInterface(thread);
verifyInterface(runnable);
}
static void verifyInterface(Class c) {
String name = c.getName();
if (c.isInterface()) {