java 反射,
分享于 点击 39884 次 点评:174
java 反射,
获取Class对象
(1)Class<?> cls = A.class(A是一个类)
(2)Class<?> cls = a.getClass()(a是A的一个对象)
(3)Class<?> cls = Class.forName("com.abc.A")(com.abc.A是类的全限定名)
判断对象的类型
(1)a instanceof A
(2)classA.isInstance(a)
interface I {}
class A {}
class B extends A implements I{}
public class Test {
public static void main(String[] args) {
A a = new B();
Class<?> bc = B.class;
Class<?> ic = I.class;
if(a instanceof B)
System.out.println("a instanceof B");
if(a instanceof A)
System.out.println("a instanceof A");
if(a instanceof I)
System.out.println("a instanceof I");
if(bc.isInstance(a))
System.out.println("bc.isInstance(a)");
if(ic.isInstance(a))
System.out.println("ic.isInstance(a)");
}
}/* output
a instanceof B
a instanceof A
a instanceof I
bc.isInstance(a)
ic.isInstance(a)
*///:~
反射
(1)我理解的反射:通过访问类的Class对象得到其属性、方法甚至构造器。
(2)类的加载使用ClassLoader。
(3)JDK为反射提供了5个类:
java.lang.Class;
java.lang.reflect.Constructor;
java.lang.reflect.Field;
java.lang.reflect.Method;
java.lang.reflect.Modifier;
动态代理
使用动态代理向文件中写入信息,发生异常时回滚。
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Operator {
boolean addInfo(File file, String s1, String s2);
}
class FileOperator implements Operator {
public boolean addInfo(File file, String s1, String s2) {
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.write(s1);
int er = 1/0;
fw.write(s2);
} catch (ArithmeticException e) {
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if(fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
}
class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
DynamicProxyHandler(Operator proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("addInfo".equals(method.getName())) {
FileReader fr = new FileReader((File)args[0]);
char[] cbuf = new char[1024];
StringBuilder sb = new StringBuilder();
while(fr.read(cbuf) != -1) {
sb.append(cbuf);
}
fr.close();
boolean b = (Boolean)method.invoke(proxied, args);
if(!b) {
System.out.println("文件修改失败,正在进行回滚!");
FileWriter fw = new FileWriter((File)args[0]);
fw.write(sb.toString());
fw.close();
}
return b;
}
return method.invoke(proxied, args);
}
}
class Test {
public static void main(String[] args) {
FileOperator fo = new FileOperator();
Operator proxy = (Operator)Proxy.newProxyInstance(
Operator.class.getClassLoader(),
new Class[] {Operator.class},
new DynamicProxyHandler(fo));
boolean b = proxy.addInfo(new File("tmp.txt"), "hello ", "world");
System.out.println(b ? "文件修改成功!" : "");
}
}
相关文章
- 暂无相关文章
用户点评