---
title: "java反射:object is not an instance of declaring class"
author: "harbey"
date: "2011-04-12T09:56:04Z"
tags: []
categories: ["编程语言"]
slug: "java-object-is-not-an-instance-of-declaring-class"
draft: false
lastmod: "2011-04-12T09:56:04Z"
id: 998502
url: "https://harbey.iteye.com/blog/998502"
---

```java

	/**
	 * <pre>
	 * <h3>通过反射执行某个方法，并将数据集放入cache中</h3>
	 * </pre>
	 * 
	 * 方法实现呆完成
	 * 
	 * @param key
	 *            缓存key
	 * @param _class
	 *            类名
	 * @param methodName
	 *            类方法名
	 * @param paramType
	 *            方法参数类型
	 * @param args
	 *            方法参数值
	 */
	public void reflect(String key, Class<T> _class, String methodName,
			Class<Object>[] paramType, Object... args) {
		try {
			// cache判断
			// 如果cache中没有这个值，则调用方法填充cache
			Method method = _class.getMethod(methodName, paramType);
			method.invoke(_class, args);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

```


执行到：

```java

method.invoke(_class, args);

```

报错：
object is not an instance of declaring class
说明Class没有实例化；
解决办法：
由于没有实力化可以有如下两种方法：
1、反射方法定义成为static的，故被反射类就不需要实例化；
2、method.invoke(_class.newInstance(), args);