【小程序】注解实现小型应用程序框架

要求:编写一个小型的应用程序框架, 该框架会向用户公开一个 run 方法,方法声明为: public void run(String className); 该方法位于类 ApplicationRun 类中,该类的声明为: 其中的字符串参数 className 为用户提供的一个类的全名 (包名+类名) ,当用户将类的全名以字符串的形式传递给该 run 方法时, 方法会自动执行用户所提供的类中的所有被 run @Test 注解所修饰的 public void 且不带参数的方法。 说明:@Test 注解为该小型应用程序框架所定义的,用户可 以使用该注解修饰自己的方法,同时该@Test 注解只能用于 修饰方法。 程序示范: 北京圣思园科技有限公司版权所有 假如用户自己定义的类为MyClass,且该类 的定义如下所示: 那么当用户调用框架提供的 run 方法时应该向 run 方法提供 参数 MyClass 字符串,

结果输出如下所示:

method2

doSomething2()

理由为:

1. method1 方法没有被@Test 注解修饰。

2. add 方法接受了参数并且有返回值。

3. doSomething 方法接受了参数 。

4. method2 方法为 public void 且不接收参数,同时被@Test 注解修饰。

5. doSomething2 方法为 public void 且不接收参数,同时被 @Test 注解修饰

框架代码

import java.lang.reflect.Method;

public class ApplicationRun
{
      public void run(String className) throws Exception 
     {
	    Class<?> classtype = Class.forName(className);
	    Object obj = classtype.newInstance();
	    Method[] methods = classtype.getMethods();
	    for(Method method:methods)
	    {
	     if (method.isAnnotationPresent(Test.class))
	     {
	    	 if("void"==method.getReturnType().getName() && 0==method.getParameterTypes().length)
	    	   method.invoke(obj,new Object[]{});
	     }
	    }
     }
}


 

注释代码

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test
{
    
}


MyClass代码

public class MyClass
{
     public void method1()
     {
    	 System.out.println("method1");
     }
    @Test
    public void method2()
    {
    	System.out.println("method2");
    }
   @Test
   public int add(int a,int b)
   {
   	return a+b;
   }
   @Test
    public void doSomething(String str)
    {
    	System.out.println(str);
    }
    @Test
    public void doSomething2()
    {
    	System.out.println("doSomething2()");
    }
    public static void main(String[] args) throws Exception  
	{
		String className = MyClass.class.getName();
		ApplicationRun testRun = new ApplicationRun();
		testRun.run(className);
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值