java 用反射将properties里面的class配置文件 ,类加载取出

默认分类 未结 1 1925
0时光机器0
0时光机器0 2023-11-27 10:40
相关标签:
1条回答
  • 2023-11-27 10:48

    这是我写的小测试程序,是不是你要的结果:首先分为两个包,一个是 com.test.properties 这个包里 有两个类:一个是Property,代码如下:package com.test.properties;public class Property { public void run() { System.out.println("run invoke!!"); }}还有一个是TestProperty测试用的,代码如下:package com.test.properties;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.lang.reflect.Method;import java.net.URL;import java.util.Properties;public class TestProperty { public static void main(String[] args) throws Exception { URL url = TestProperty.class.getResource("/"); String basePath = url.getPath().substring(1); String path = basePath + "properties/class.properties"; InputStream input = new FileInputStream(new File(path)); Properties ps = new Properties(); ps.load(input); String cPath = ps.getProperty("Property"); Class pClass = Class.forName(cPath); Object instance = pClass.newInstance(); Method[] methods = pClass.getDeclaredMethods(); for(Method m : methods){ m.invoke(instance, new Object[]{}); } }}还有一个包是 :properties包,有个 属性文件:class.properties内容如下:Property=com.test.properties.Property这是全部测试数据。希望能帮到你

    static ClassforName(String className) 得到 class Method getDeclaredMethod(String name, Class... parameterTypes) Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. Method[] getDeclaredMethods() Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.

    0 讨论(0)
提交回复