java 反射 获取方法_Java反射获取方法和属性

获取方法

getMethod(String name, Class>... parameterTypes) 返回类中的某个公共方法-包括父类中的公共方法

getMethods()返回方法数组 下同

getDeclaredMethod(String name, Class>... parameterTypes) 返回类中所有方法-包括私有方法

获取属性

getField(String name) 返回pubilc属性- 包括父类

getFields() 返回属性数组 下同

getDeclaredField(String name)返回所有属性-不包括父类

//default包中的Test03类

public classTest03 {public String a = "Test03的public字符串";private String b = "Test03的private字符串";public voidshow(){

System.out.println("hi huang!");

}

private void show_private(){

System.out.println("this is a peivate method");

}public voidshow(String str, String s){

System.out.println(str+s);

}

}

package lei;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class Test04 {

public static void main(String[] args){

//用反射调用default包里的Test03类中的无参show方法 第二个参数也可以写null 这里空着

try{

Class> c = Class.forName("Test03");

Method method = c.getMethod("show");

System.out.println(method);

method.invoke(c.newInstance());

}catch(Exception e){

}

//用反射调用default包里的Test03类中的参数为两个String的show方法

try{

Class> c = Class.forName("Test03");

Method method = c.getMethod("show", String.class, String.class);

System.out.println(method);

//String[] varArgs = {"shixin", "zhang"};

method.invoke(c.newInstance(), "hi men", "!!!");

}catch(Exception e){

}

//调用Test03中的私有无参方法

try{

Class> c = Class.forName("Test03");

Method method = c.getDeclaredMethod("show_private");

method.setAccessible(true);

System.out.println(method);

method.invoke(c.newInstance());

}catch(Exception e){

}

//反射实例化Test03类 打印Test03中所有属性

try{

Class> c = Class.forName("Test03");

Field[] fields = c.getDeclaredFields();

Field f = c.getField("a");

System.out.println(f.get(new T()));

for (Field field: fields){

field.setAccessible(true);

System.out.println(field);

System.out.println(field.get(new T()));

}

}catch(Exception e){

}

//反射实例化Test03类 打印Test03中私有属性

try{

Class> c = Class.forName("Test03");

Field f = c.getDeclaredField("b");

f.setAccessible(true);

System.out.println(f);

System.out.println(f.get(c.newInstance()));

}catch(Exception e){

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值