简单的Java反射机制

一. 创建一个简单的java类如下:

package cn.zq;

public class SomeClass {

/**
* 转换成小写
**/
public void toLower(String s)
{
System.out.println("toLower方法");
System.out.println("原字符:"+s);
System.out.println("转换后:"+s.toLowerCase()) ;

}

/**
* 转换成大写
**/
public void toUpper(String s)
{
System.out.println("toUpper方法");
System.out.println("原字符:"+s);
System.out.println("转换后:"+s.toUpperCase()) ;
}
}


二. 创建反射类

package cn.zq;

import java.lang.reflect.InvocationTargetException;

public class TestRefl {

public void test1(String action) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
Class clazz = Class.forName(action);

SomeClass c = (SomeClass) clazz.newInstance();

c.toUpper("ffff");

c.toLower("AAAA");


}



public static void main(String[] args) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
TestRefl tr = new TestRefl();
tr.test1("cn.zq.SomeClass");
}
}

结果如图

反射类也可以写成如下

package cn.zq;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestRefl {

public void test1(String action) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
Class clazz = Class.forName(action);

SomeClass c = (SomeClass) clazz.newInstance();

Method m = clazz.getMethod("toLower", new Class[]{String.class});

m.invoke(c, new Object[]{"STR"});

Method m2 = clazz.getMethod("toUpper", new Class[]{String.class});

m2.invoke(c, new Object[]{"str"});


}



public static void main(String[] args) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
TestRefl tr = new TestRefl();
tr.test1("cn.zq.SomeClass");
}
}

结果如下

结果显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值