java反射 例子_JAVA反射 看视频写的一个例子

package com.stu.reflection;

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

import org.junit.Test;

/**

* @author Administrator

* 反射的练习,

* ,

*

*

*/

public class Reflect {

/**

* 反射类的构造方法

*

*/

@Test

public void getRefectClass() throws Exception{

//加载需要反射的类

Class clazz = Class.forName("com.stu.reflection.Wook");

Constructor co = clazz.getConstructor(null);//指定无参数的构造方法

co.newInstance();//调用

Constructor co1 = clazz.getConstructor(String.class,String.class);//指定有参数的构造方法

co1.newInstance("admin","passowrd");//调用 传递参数

//指定被私有化的构造方法,采用getDeclaredConstructor

Constructor co2 = clazz.getDeclaredConstructor(List.class);

co2.setAccessible(true);//强制设置私有的构造方法能够被访问

co2.newInstance(new ArrayList());//调用传参

}

/**

* 反射类的方法

* @throws Exception

*/

@Test

public void getRefectByMethod() throws Exception{

//加载需要反射的类

Wook wk = new Wook();

Class clazz = Class.forName("com.stu.reflection.Wook");

Method mo = clazz.getMethod("loginIn", String.class,String.class);

mo.invoke(wk, "admin","password");

Method mo1 = clazz.getMethod("loginOut", String.class);

mo1.invoke(wk, "admin");

//访问静态方法

Method mo2 = clazz.getDeclaredMethod("saveMethod", null);

mo2.setAccessible(true);

mo2.invoke(wk,null);

}

/**

* 反射类的属性

* @throws Exception

*/

@Test

public void getRefectByField() throws Exception{

Wook wk = new Wook();

Class clazz = Class.forName("com.stu.reflection.Wook");

//clazz.newInstance() 相当于 Wook wk = new Wook();

Field fd1 = clazz.getField("aaa");

fd1.get(wk);

Field fd = clazz.getDeclaredField("username");

fd.setAccessible(true);

System.out.println(fd.getName());

// 循环访问静态方法

Field[] fds = clazz.getDeclaredFields();

for (Field f : fds) {

PropertyDescriptor pd = new PropertyDescriptor(f.getName(), Wook.class);

Method md = pd.getWriteMethod();

md.invoke(wk, "admin");//给属性复制

}

for (Field f : fds) {

PropertyDescriptor pd = new PropertyDescriptor(f.getName(), Wook.class);

Method md = pd.getReadMethod();//读取属性值

System.out.println(md.invoke(wk));

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值