zoukankan      html  css  js  c++  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;

    }

    }

  • 相关阅读:
    再谈算法复杂度
    Android 升级ADT到22第三方Jar包导致的ClassNotFoundException和NoClassDefFoundError异常解决
    spring security 3.1 实现权限控制
    Mysql又一次整理笔记--woods备忘
    从头认识Spring-3.8 简单的AOP日志实现(注解版)-扩展添加检查订单功能,以便记录并检測输入的參数
    Knockout JS 演示样例
    gulp初探
    [android] 线性布局和布局的组合
    [android] 相对布局和单位简介
    [android] 短信发送器
  • 原文地址:https://www.cnblogs.com/xiaweicn/p/8666568.html
Copyright © 2011-2022 走看看