• 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;

    }

    }

  • 相关阅读:
    leetcode笔记--7 Find the Difference
    数据挖掘:概念与技术--笔记1--度量数据的相似性与相异性
    leetcode笔记--6 Add Digits
    leetcode 笔记5 single number
    数据挖掘导论笔记2 数据集的类型
    **leetcode笔记--4 Sum of Two Integers
    vs2015-Cordova开发安卓应用环境搭建
    c#一些常用的方法集合
    c#根据ip获取城市地址
    asp.net mvc 无刷新加载
  • 原文地址:https://www.cnblogs.com/xiaweicn/p/8666568.html
Copyright © 2020-2023  润新知