您的位置:首页 > 编程语言 > Java开发

关于java反射机制的学习

2017-06-27 15:08 399 查看
package day05;

import day04.NioTest;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.Arrays;

class Reflect {

public Reflect(String s){
System.out.println("String construction"+s);
}
public Reflect(int i){
System.out.println("int construction"+i);
}
private int i;

private String string;

public int ii;

public String strings;

public int getI() {
return i;
}

public void setI(int i) {
this.i = i;
}

public void stringmethodstring(String s){
System.out.println("stringmethodstring"+"---"+s);
}

public void stringmethod(){
System.out.println("stringmethod");
}

private void privatemethod(){
System.out.println("privatemethod----");
}
}

interface Myinterface{
void dosth(String ss);
void doot();
}

public class reflectLearn{

public static void main(String[] args) {
Reflect reflect = new Reflect("s");

//        NioTest nioTest = new NioTest();
Class cla = Reflect.class;
Class cla1 = NioTest.class;
System.out.println(cla.getName());//获取带包名的类名
System.out.println(cla.getSimpleName());//获取不带包名的类名
System.out.println(cla1.getModifiers());//获取权限修饰符,枚举类型
System.out.println(Modifier.isPublic(cla1.getModifiers()));//判断修饰符
Package pa = cla.getPackage();//获取包信息
Class superclass = cla.getSuperclass();//获取父类
Class[] classes = cla.getInterfaces();//获取实现的接口
Annotation[] annotations = cla.getAnnotations();//获取注解
Constructor[] constructors = cla.getConstructors();//获取构造器

try{
Constructor constructor = cla.getConstructor(String.class);//获取指定参数(String)的构造器
Reflect reflect1 = (Reflect) constructor.newInstance("sth");//用构造函数实例化一个类

Field[] fields = cla.getFields();//获取变量
System.out.println("变量:"+ Arrays.asList(fields));
Field field = cla.getField("ii");
System.out.println("获取指定变量:"+field.getName()+"变量类型是:"+field.getType().getName());
field.set(reflect,2);
System.out.println("field的set和get方法:"+field.get(reflect));

Method[] methods = cla.getMethods();//获取方法
Method method = cla.getMethod("stringmethodstring", String.class);//获取指定方法
method.invoke(reflect,"sth");
method = cla.getDeclaredMethod("privatemethod");
method.setAccessible(true);//获取private和public和protected成员属性和方法
method.invoke(reflect);

Myinterface proxy = (Myinterface)Proxy.newProxyInstance(Myinterface.class.getClassLoader(),
new Class[]{Myinterface.class},new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                    System.out.println("--invoke--");
//                    method.invoke(proxy);
if(method.getName().equals("dosth")){
System.out.println("invoke----dosth"+args[0]);
}else {
System.out.println("invoke----doot");
}
return null;
}
});
proxy.dosth("?");
proxy.doot();
}catch (Exception e){
System.out.println("????");
}

}

}另外,动态代理和类加载不是很理解,以后再学习吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 动态代理