zoukankan      html  css  js  c++  java
  • Java反射特性--获取其他类实例并调用其方法

    1. 代码结构

    .
    ├── com
    │   └── test
    │      └── MyTest.java
    └── MainCall.java

    2. 代码内容

    MyTest.java:

    package com.test;
    
    public class MyTest
    {
        public void do_test() 
        {
            System.out.println("Doing test...
    ");
        }
    }

    MaiCall.java

    import java.lang.reflect.Method;
    
    public class MainCall
    {
        public static void main(String[] args)
        {
            System.out.println("Hello World!
    ");
    
            Class<?> mt = null;
            try{
                mt = Class.forName("com.test.MyTest");
            }catch(Exception e) {
                e.printStackTrace();
            }
    
            System.out.println("ClassName: " + mt.getName());
            
            try{
                Method method = mt.getMethod("do_test");
                method.invoke(mt.newInstance());
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    3.编译

    javac com/test/MyTest.java

    javac MainCall.java

    编译成功后:

    .
    ├── com
    │   └── test
    │      ├── MyTest.class
    │      └── MyTest.java
    ├── MainCall.class
    └── MainCall.java

    4. 执行

    java MainCall得到输出:

    Hello World!

    ClassName: com.test.MyTest
    Doing test...

  • 相关阅读:
    GNU GPL介绍
    《Getting Started with WebRTC》第一章 WebRTC介绍
    进一步解 apt-get 的几个命令
    状态模式----C++实现
    boost库asio详解1——strand与io_service区别
    Timer.5
    Timer.4
    Timer.3
    MFC定时器
    boost.asio系列——Timer
  • 原文地址:https://www.cnblogs.com/yanghaizhou/p/5917997.html
Copyright © 2011-2022 走看看