问题解决:java-反射-ClassNotFound报错解决

 

1.在文件夹跑java RunTest.java 是OK的,进入到eclipse里面,同样的代码,会报错ClassNotFound

public class RunTests
{
	public static void main(String[] args)
		throws Exception
	{
		// 处理MyTest类
		ProcessorTest.process("MyTest");
	}
}

package chapter14;

import java.lang.reflect.*;

public class TestProcessor
{
	public static void process(String clazz)
		throws ClassNotFoundException
	{
		int passed = 0;
		int failed = 0;
		// 遍历clazz对应的类里的所有方法
		for (Method m : Class.forName(clazz).getMethods())
		{
			// 如果该方法使用了@Testable修饰
			if (m.isAnnotationPresent(Testable.class))
			{
				try
				{
					// 调用m方法
					m.invoke(null);
					// 测试成功,passed计数器加1
					passed++;
				}
				catch (Exception ex)
				{
					System.out.println("方法" + m + "运行失败,异常:"
						+ ex.getCause());
					// 测试出现异常,failed计数器加1
					failed++;
				}
			}
		}
		// 统计测试结果
		System.out.println("共运行了:" + (passed + failed)
			+ "个方法,其中:\n" + "失败了:" + failed + "个,\n"
			+ "成功了:" + passed + "个!");
	}
}
package chapter14;

public class MyTest {
	@Testable
	public static void m1(){}
	public static void m2(){}
	@Testable
	public static void m3(){
		throw new RuntimeException("Boom");
	}
	public static void m4(){}
	@Testable
	public static void m5(){}
	public static void m6(){}
	@Testable
	public static void m7(){
		throw new RuntimeException("Crash");
	}
	public static void m8(){}
}
package chapter14;

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

  说我的MyTest不存在。搜了一下,是package的问题,className没有写全。

要在className前面加上packge:

package chapter14;

public class RunTests {
	public static void main(String[]args)
	throws Exception
	{
		TestProcessor.process("chapter14.MyTest");
	}
}

  

参考:

https://ask.csdn.net/questions/203230

 

posted @ 2018-05-25 17:22  头鹰在学习  阅读(3864)  评论(0编辑  收藏  举报