Java 反射实例

本文详细介绍了如何使用Java反射机制创建对象并调用方法。通过具体的代码示例展示了反射生成带参数对象的过程,以及如何利用反射机制调用类的方法。

package com.xiawei.reflect.reflectservice;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 反射生成对象(有参数的)
* @author Administrator
*
*/
public class ReflectServiceClassImpl1 {

private String name;

public ReflectServiceClassImpl1(String name) {
this.name = name;
}

public void say(String name) {
System.out.println("你好啊,"+name);
}

public ReflectServiceClassImpl1 getInstance(){
ReflectServiceClassImpl1 object = null;
try {

object = (ReflectServiceClassImpl1) Class.forName("com.xiawei.reflect.reflectservice.ReflectServiceClassImpl").
getConstructor(String.class).newInstance("张三");

} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
return object;

}

/**
* 反射方法
* @return
*/
public Object reflectMethod(){
Object returnObj = null;
ReflectServiceClassImpl target = new ReflectServiceClassImpl();

Method method = null;
try {

method = ReflectServiceClassImpl.class.getMethod("say", String.class);
returnObj = method.invoke(target, "张三");

} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}

return returnObj;

}

/**
* 反射生成对象,和反射调度方法
* @return
*/
public Object reflect(){
ReflectServiceClassImpl object = null;
try {
//通过反射获得对象
object = (ReflectServiceClassImpl)
Class.forName("com.xiawei.reflect.reflectservice.ReflectServiceClassImpl").newInstance();
//通过对象反射获得方法
Method method = object.getClass().getMethod("say", String.class);
//执行方法
method.invoke(object, "张三");

} catch (NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| ClassNotFoundException | IllegalArgumentException
| InvocationTargetException e) {

e.printStackTrace();
}
return object;

}

}

转载于:https://www.cnblogs.com/xiaweicn/p/8666568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值