java.lang.reflect.InvocationTargetException的一个可能原因

合集下载

java.lang.reflect.InvocationTargetException的一个可能原因

java.lang.reflect.InvocationTargetException的一个可能原因

ng.reflect.InvocationTargetException的一个可能原因各位读友大家好!你有你的木棉,我有我的文章,为了你的木棉,应读我的文章!若为比翼双飞鸟,定是人间有情人!若读此篇优秀文,必成天上比翼鸟!ng.reflect.InvocationTargetException的一个可能原因这几天项目正在不断测试、演示中,当我把项目交给测试和实施部的时候项目一切运行正常,可是昨天一实施人员告诉我,系统部署到tomcat中启动运行报出了一个异常,发给我看了一下,我的个乖乖,这个异常信息这么久我还是头一次看见,于是赶紧的上网查了一下资料,后来通过各种测试,环境搭建模拟发现产生该异常信息的主要原因可能是一下几点:1、包冲突、有重复包或者缺少包2、项目jdk和部署jdk版本不一样,导致InvocationTargetException异常信息返回一个空值,没有调用invoc里的重写消息方法。

3、映射文件发生改变对于不同原因的解决:1、包:直接自己挨着查看就是了,但是一定要注意遇到重复包的时候你的系统究竟需要哪一个版本2、jdk版本:⑴、更换jdk包⑵、用一个方法统一处理该异常private static void handleException(Exception e){String msg=null;if(e instanceof InvocationTargetException){ThrowabletargetEx=((InvocationTargetException)e).getTargetException();if(tar getExt!=null){msg=targetEx.getMessage();}}else{msg=e.getMessage();} MessageDialong.openError(Activator.getDetDefault().getWorkbenc h().getDisplay().getActiveshell(),”error”,msg);e.printStackTrace();}3、映射文件发生改变在项目中有的地方是使用反射机制进行的操作,可能对于类进行了某些更改,科室映射文件没有更改,采用匿名就会出现这样的问题,解决办法要么更改映射文件,要不不要使用匿名调用各位读友大家好!你有你的木棉,我有我的文章,为了你的木棉,应读我的文章!若为比翼双飞鸟,定是人间有情人!若读此篇优秀文,必成天上比翼鸟!。

安卓亮度调节代码

安卓亮度调节代码

package com.kunge.powermanage.tools;public class Light {package com.example.bs;import ng.reflect.Field;import ng.reflect.InvocationTargetException;import ng.reflect.Method;import android.app.Activity;import android.content.ContentResolver;import android.content.Context;import android.database.ContentObserver;import android.os.Bundle;import android.os.Handler;import android.os.PowerManager;import android.provider.Settings;import android.provider.Settings.SettingNotFoundException;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class BrightnessSwitch extends Activity implements OnClickListener {private Button mBrightness;private static final int LIGHT_NORMAL = 64;private static final int LIGHT_50_PERCENT = 127;private static final int LIGHT_75_PERCENT = 191;private static final int LIGHT_100_PERCENT = 255;private static final int LIGHT_AUTO = 0;private static final int LIGHT_ERR = -1;private BrightObserver mBrightObserver;private PowerManager mPowerManager;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);mBrightObserver = new BrightObserver(new Handler());mBrightness = (Button)findViewById(R.id.bright); refreshButton();mBrightness.setOnClickListener(this);}@Overrideprotected void onDestroy(){// TODO Auto-generated method stubsuper.onDestroy();mBrightObserver.stopObserver();}@Overrideprotected void onResume(){// TODO Auto-generated method stubsuper.onResume();mBrightObserver.startObserver();}//更新按钮private void refreshButton(){switch (getBrightStatus()){case LIGHT_NORMAL:mBrightness.setText(R.string.light_50percent); break;case LIGHT_50_PERCENT:mBrightness.setText(R.string.light_75percent); break;case LIGHT_75_PERCENT:mBrightness.setText(R.string.light_100percent); break;case LIGHT_100_PERCENT:mBrightness.setText(R.string.light_auto);break;case LIGHT_AUTO:mBrightness.setText(R.string.light_normal);break;case LIGHT_ERR:mBrightness.setText(R.string.light_err);break;}}//得到当前亮度值状态private int getBrightStatus(){// TODO Auto-generated method stubint light = 0;boolean auto = false;ContentResolver cr = getContentResolver();try{auto = Settings.System.getInt(cr,Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;if (!auto){light = android.provider.Settings.System.getInt(cr,Settings.System.SCREEN_BRIGHTNESS, -1);if (light > 0 && light <= LIGHT_NORMAL){return LIGHT_NORMAL;}else if (light > LIGHT_NORMAL && light <= LIGHT_50_PERCENT) {return LIGHT_50_PERCENT;}else if (light > LIGHT_50_PERCENT && light <= LIGHT_75_PERCENT) {return LIGHT_75_PERCENT;}else if (light > LIGHT_75_PERCENT && light <= LIGHT_100_PERCENT) {return LIGHT_100_PERCENT;}}else{return LIGHT_AUTO;}}catch (SettingNotFoundException e1){// TODO Auto-generated catch blocke1.printStackTrace();}return LIGHT_ERR;}private void setBrightStatus(){int light = 0;switch (getBrightStatus()){case LIGHT_NORMAL:light = LIGHT_50_PERCENT - 1;break;case LIGHT_50_PERCENT:light = LIGHT_75_PERCENT - 1;break;case LIGHT_75_PERCENT:light = LIGHT_100_PERCENT - 1;break;case LIGHT_100_PERCENT:startAutoBrightness(getContentResolver());break;case LIGHT_AUTO:light = LIGHT_NORMAL - 1;stopAutoBrightness(getContentResolver());break;case LIGHT_ERR:light = LIGHT_NORMAL - 1;break;}setLight(light);setScreenLightValue(getContentResolver(), light); }/*因为PowerManager提供的函数setBacklightBrightness接口是隐藏的,* 所以在基于第三方开发调用该函数时,只能通过反射实现在运行时调用*/private void setLight(int light){try{//得到PowerManager类对应的Class对象Class<?> pmClass = Class.forName(mPowerManager.getClass().getName());//得到PowerManager类中的成员mService(mService为PowerManagerService类型)Field field = pmClass.getDeclaredField("mService");field.setAccessible(true);//实例化mServiceObject iPM = field.get(mPowerManager);//得到PowerManagerService对应的Class对象Class<?> iPMClass = Class.forName(iPM.getClass().getName());/*得到PowerManagerService的函数setBacklightBrightness对应的Method对象,* PowerManager的函数setBacklightBrightness实现在PowerManagerService中*/Method method = iPMClass.getDeclaredMethod("setBacklightBrightness", int.class);method.setAccessible(true);//调用实现PowerManagerService的setBacklightBrightnessmethod.invoke(iPM, light);}catch (ClassNotFoundException e){// TODO Auto-generated catch blocke.printStackTrace();}catch (NoSuchFieldException e){// TODO Auto-generated catch blocke.printStackTrace();}catch (IllegalArgumentException e){// TODO Auto-generated catch blocke.printStackTrace();}catch (IllegalAccessException e){// TODO Auto-generated catch blocke.printStackTrace();}catch (NoSuchMethodException e){// TODO Auto-generated catch blocke.printStackTrace();}catch (InvocationTargetException e){// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void onClick(View v){// TODO Auto-generated method stubsetBrightStatus();}//启动自动调节亮度public void startAutoBrightness(ContentResolver cr){Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);}//关闭自动调节亮度public void stopAutoBrightness(ContentResolver cr){Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);}//设置改变亮度值public void setScreenLightValue(ContentResolver resolver, int value) {android.provider.Settings.System.putInt(resolver,Settings.System.SCREEN_BRIGHTNESS,value);}private class BrightObserver extends ContentObserver{ContentResolver mResolver;public BrightObserver(Handler handler){super(handler);mResolver = getContentResolver();}@Overridepublic void onChange(boolean selfChange){// TODO Auto-generated method stubsuper.onChange(selfChange);refreshButton();Toast.makeText(BrightnessSwitch.this, "亮度设置有改变", Toast.LENGTH_SHORT).show();}//注册观察public void startObserver(){mResolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), false, this);mResolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE), false,this);}//解除观察public void stopObserver(){mResolver.unregisterContentObserver(this);}}}权限添加:[html] view plaincopy<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.DEVICE_POWER" /> }。

《Java基础知识》Java动态代理(InvocationHandler)详解

《Java基础知识》Java动态代理(InvocationHandler)详解

《Java基础知识》Java动态代理(InvocationHandler)详解1. 什么是动态代理对象的执⾏⽅法,交给代理来负责。

⽐如user.get() ⽅法,是User对象亲⾃去执⾏。

⽽使⽤代理则是由proxy去执⾏get⽅法。

举例:投资商找明星拍⼴告,投资商是通过经纪⼈联系的,经纪⼈可以帮明星接这个⼴告,也可以拒绝。

做不做,怎么做都叫给经纪⼈和投资商谈。

2. 实际场景应⽤2.1 校验⽤户权限,每⼀个菜单请求,都要判断⼀下请求的⽤户是否有该菜单权限。

菜单多了,代码冗余,且容易遗漏。

通过动态代理就可以实现为:每⼀个⽤户,每⼀个菜单的请求,都经过代理(proxy),由他判断是否有权限,调⽤者只需要调⽤,实现⾃⼰的逻辑,不关⼼权限问题。

3. 动态代理完整案例:/*** 创建⽤户接⼝*/public interface UserBean {String getUser();}import erBean;public class UserBeanImpl implements UserBean {private String user = null;//flag:0 ⽆权限,1有权限。

private String flag = null;public String getFlag() {return flag;}public void setFlag(String flag) {this.flag = flag;}public UserBeanImpl(String user,String flag){er = user;this.flag = flag;}public String getUserName(){return user;}public String getUser(){System.out.println("this is getUser() method!");return user;}public void setUser(String user){er = user;System.out.println("this is setUser() method!");}}import ng.reflect.InvocationHandler;import ng.reflect.Method;public class UserBeanProxy implements InvocationHandler {private Object targetObject;public UserBeanProxy(Object targetObject){this.targetObject = targetObject;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {UserBeanImpl userBean = (UserBeanImpl) targetObject;String flag = userBean.getFlag();Object result = null;//权限判断if("1".equals(flag) ){result = method.invoke(targetObject, args);}else{System.out.println("sorry , You don't have permission");}return result;}}import erBean;import ng.reflect.Proxy;public class TestSection {public static void main(String[] args) {UserBeanImpl targetObject = new UserBeanImpl("蕾蕾","1");UserBeanProxy proxy = new UserBeanProxy(targetObject);//⽣成代理对象UserBean object = (UserBean) Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), proxy);String userName = object.getUser();System.out.println("userName: " + userName);}}运⾏结果:代理代理核⼼代码UserBean object = (UserBean) Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),targetObject.getClass().getInterfaces(), proxy);public interface InvocationHandler {public Object invoke(Object proxy, Method method, Object[] args)throws Throwable;}接⼝:InvocationHandler,代理需要实现该接⼝,并且实现⽅法:invoke。

本地tomcat调用远程接口报错:java.lang.reflect.Invocation。。。

本地tomcat调用远程接口报错:java.lang.reflect.Invocation。。。

本地tomcat调⽤远程接⼝报错:ng.reflect.Invocation。

今天碰到⼀个奇怪的问题,本地Eclipse起了⼀个tomcat通过http去调⼀个外部接⼝,结果竟然报了⼀个反射的异常——ng.reflect.InvocationTargetException,从⽇志⾥看不出啥来,通过eclipse调试发⽣了诡异的事情——直接跳⼊异常了 /*** Constructs a InvocationTargetException with a target exception.** @param target the target exception*/public InvocationTargetException(Throwable target) {super((Throwable)null); // Disallow initCausethis.target = target;} 从异常看,是程序找不到调⽤代码了,但是eclipse⾥⾯是可以找到调⽤类和⽅法的。

想了⼀下,应该是编译出问题了,或许class⽂件⾥没有应的代码。

去eclipse部署的本地tomcat路径下找class:打开Servers窗⼝ -> 找到Server Locations,看Server path和Deploy path,进⼊本地部署路径: 进⼊wtpwebapps -> 进⼊war包 -> 找到引⽤的jar -> 打开jar包,根据包路径找类,果然没有调⽤类。

估计是之前引⽤的jar包编译出了问题。

解决办法:重新编译问题jar包,刷新引⽤jar包的⼯程,最后clean⼀下tomcat,再次进⼊到tomcat本地部署路径E:\workspace.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebapps,发现调⽤类出现了,重新启动tomcat,问题依然存在。

java运行时异常

java运行时异常

ng.OutOfMemoryError: PermGen space 内存溢出未解决?????????????不明白为什么,什么错误导致的javax.servlet.ServletException:Request[/yhb] does not contain handler parameter named ‘method’. This may be caused by whitespace in the label text.解决:form表单中缺少提交方法method=post/getng.ClassCastException: [ng.Object;atcom.carry.service.impl.YhbManagerImpl.loginCheck(YhbManagerImpl.java: 44)javax.servlet.ServletException:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannotopen connectionng.NoClassDefFoundError:org/eclipse/jdt/internal/compiler/ast/ArrayTypeReference解决办法:内存溢出,重新启动服务器METHOD传参数方法找不到,ACTION中,方法的四个参数顺序不能颠倒tsList(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception异常:不能连接数据库(解决:数据库连接不上,连接异常,1,检查网络连接,2,检查是否有连接驱动,)Could not obtain connection metadatamons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory(Io异常: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=150999297)(ERR=12505)(ERROR_STACK=( ERROR=(CODE=12505)(EMFI=4)))))连接拒绝[SettingsFactory] Could not obtain connection metadatamons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory(Io异常: The Network Adapter could not establish the connection)网络适配器不能建立连接,ORACLE数据库服务器没有打开java.io.IOException: tmpFile.renameTo(classFile) failed解决:JSP文件中有不能运行的JAVA代码!Unable to find a value for “id”in object of class “ng.String”using operator “.”解决:<c:forEach var=”fun”items=”${listFun}”><c:forEach> 中的items=”${listFun}”错写为items=”listFun”Illegal use of &lt;when&gt;-style tag without &lt;choose&gt; as its direct parent”${map.yuanYouPur=’yuanYouPur’}”contains invalid expression(s): javax.servlet.jsp.el.ELException: Encountered “=”, expectedone of [”]”, “.”, “>”, “gt”, “<”, “lt”, “==”, “eq”, “<=”, “le”, “>=”, “ge”, “!=”, “ne”, “[”, “+”, “-“, “*”, “/”, “div”, “%”,“mod”, “and”, “&&”, “or”, “||”, “?”]解决:JSTL语言表达使用错误!The “.”operator was supplied with an index value of type “ng.String” to be applied to a List or array, but that valuecannot be converted to an integer.解决:JSP页面中,用‘ ${} ’输出获得的对象的属性,使用错误,例如返回LIST数组,其中存的对象是OBJ(页面中可以定义变量obj代表一个OBJ),取OBJ的属性AGE,NAME, 应该是${obj.age} ${}即可获得OBJ的AGE和NAME属性值,检查在使用${}的地方${obj.age} ${}是否正确,异常不能正常打开JSP文件!(2007.08.31) enough of enjoyment and comfort Unable to create this part due to an internal error. Reason for the failure: Widget is disposedorg.eclipse.swt.SWTException: Widget is disposed解决方法:1到window-preference-general-editors-file associations下看看你的*.html默认打开方式是什么。

java反射调用不定项参数方法

java反射调用不定项参数方法

java反射调用不定项参数方法Java反射是Java语言的特性之一,它允许程序在运行时动态地获取类的信息,并且可以在运行时动态地调用类的方法。

在Java反射中,有一种方法叫做不定项参数方法,它是指可以接受任意数量的参数的方法。

在Java中,不定项参数方法的声明方式是在方法名后面加上三个点(...),例如:public void printValues(String... values) {for(String value : values) {System.out.println(value);}}在这个例子中,printValues()方法可以接受任意数量的字符串参数,并且在方法体内打印输出这些参数。

如果我们想要通过Java反射调用这个不定项参数方法,可以使用以下代码:Class<?> clazz = MyClass.class; //获取MyClass类的Class 对象Method method = clazz.getDeclaredMethod('printValues', String[].class); //获取printValues方法的Method对象method.invoke(new MyClass(), new Object[]{newString[]{'value1', 'value2', 'value3'}}); //通过invoke方法调用printValues方法在这个例子中,我们首先使用反射获取MyClass类的Class对象,然后再使用getDeclaredMethod()方法获取printValues方法的Method对象。

需要注意的是,在getDeclaredMethod()方法中,我们需要传入一个String[].class参数,来告诉Java反射这个方法是一个不定项参数方法。

最后一行代码中,我们使用invoke()方法来调用printValues方法。

java.lang.reflect.InvocationTargetException的一个可能原因

java.lang.reflect.InvocationTargetException的一个可能原因

ng.reflect.InvocationTargetException的一个可能原因ng.reflect.InvocationTargetException的一个可能原因这几天项目正在不断测试、演示中,当我把项目交给测试和实施部的时候项目一切运行正常,可是昨天一实施人员告诉我,系统部署到tomcat中启动运行报出了一个异常,发给我看了一下,我的个乖乖,这个异常信息这么久我还是头一次看见,于是赶紧的上网查了一下资料,后来通过各种测试,环境搭建模拟发现产生该异常信息的主要原因可能是一下几点:1、包冲突、有重复包或者缺少包2、项目jdk和部署jdk版本不一样,导致InvocationTargetException异常信息返回一个空值,没有调用invoc里的重写消息方法。

3、映射文件发生改变对于不同原因的解决:1、包:直接自己挨着查看就是了,但是一定要注意遇到重复包的时候你的系统究竟需要哪一个版本2、jdk版本:⑴、更换jdk包⑵、用一个方法统一处理该异常private static void handleException(Exception e){String msg=null;if(e instanceof InvocationTargetException){Throwable targetEx=((InvocationTargetException)e).getTargetException();if(targetEx t!=null){msg=targetEx.getMessage();}}else{msg=e.getMessage();}MessageDialong.openError(Activator.getDetDefault().getWorkbench().getDisplay().getActiveshel l(),”error”,msg);e.printStackTrace();}3、映射文件发生改变在项目中有的地方是使用反射机制进行的操作,可能对于类进行了某些更改,科室映射文件没有更改,采用匿名就会出现这样的问题,解决办法要么更改映射文件,要不不要使用匿名调用。

动态加载JAR包与Method方法调用

动态加载JAR包与Method方法调用
try {
List<Class> classList = new ArrayList<Class>();
classList.add(String.class);
classList.add(int.class);
Class[] classes = new Class[classList.size()];
public String getNameAndAge(String name, int age, String address){
return name + "name is " + name +" and age is " + (age-10) + " ans address is " + address;
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
URL _url;
try {
_url = new URL(url);
URLClassLoader loader = new URLClassLoader(new URL[] { _url });
try {
Class cls = loader
.loadClass("demo.LoaderTest");
e.printStackTrace();
}
} catch (ClassNotFoundException e) {

java反射执行带参数的方法

java反射执行带参数的方法

java反射执行带参数的方法不多说,直接贴代码,不懂查API,现在就列取要用的方法和类。

Class类:public MethodgetDeclaredMethod(String name,Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException返回一个Method 对象,该对象反映此Class 对象所表示的类或接口的指定已声明方法。

name 参数是一个String,它指定所需方法的简称,parameterTypes 参数是Class 对象的一个数组,它按声明顺序标识该方法的形参类型。

如果在某个类中声明了带有相同参数类型的多个方法,并且其中有一个方法的返回类型比其他方法的返回类型都特殊,则返回该方法;否则将从中任选一个方法。

如果名称是"<init>” 或“<clinit>",则引发一个NoSuchMethodException。

参数:name - 方法名parameterTypes - 参数数组返回:该类与指定名和参数相匹配的方法的Method 对象抛出:NoSuchMethodException - 如果找不到匹配的方法。

NullPointerException - 如果name 为nullSecurityException - 如果存在安全管理器s,并满足下列任一条件:从以下版本开始:JDK1.1Method类:public Objectinvoke(Object obj, Object... args) throws IllegalAccessException,IllegalArgumentException, InvocationTargetException对带有指定参数的指定对象调用由此Method 对象表示的底层方法。

个别参数被自动解包,以便与基本形参相匹配,基本参数和引用参数都随需服从方法调用转换。

Java异常处理之InvocationTargetException(反射异常)

Java异常处理之InvocationTargetException(反射异常)

Java异常处理之InvocationTargetException(反射异常)Java异常处理之InvocationTargetException(反射异常)InvocationTargetException异常由Method.invoke(obj, args...)⽅法抛出。

当被调⽤的⽅法的内部抛出了异常⽽没有被捕获时,将由此异常接收⽰例:1. package com.zzj.test.reflect;2.3. public class Reflect {4. public void run(int i) throws ZeroException {5. B b = new B();6. b.run(i);7. }8. }9.10. class B {11. public void run(int i) throws ZeroException {12. if (i < 0) {13. throw new ZeroException("参数不能⼩于零!");14. }15. System.out.println("参数:" + i);16.17. }18. }19.20. class ZeroException extends Exception {21. private static final long serialVersionUID = 1L;22.23. private String detailMessage;24.25. public ZeroException(String detailMessage) {26. this.detailMessage = detailMessage;27. }28.29. public String getMessage() {30. return detailMessage;31. }32. }测试:1. package com.zzj.test.reflect;2.3. import ng.reflect.InvocationTargetException;4. import ng.reflect.Method;5.6. public class Test {7. public static void main(String[] args) {8. try {9. Class<?> clazz = Class.forName("com.zzj.test.reflect.Reflect");10. Method method = clazz.getMethod("run", int.class);11. method.invoke(clazz.newInstance(), -1);12. } catch (ClassNotFoundException e) {13. e.printStackTrace();14. } catch (SecurityException e) {15. e.printStackTrace();16. } catch (NoSuchMethodException e) {17. e.printStackTrace();18. } catch (IllegalArgumentException e) {19. e.printStackTrace();20. } catch (IllegalAccessException e) {21. e.printStackTrace();22. } catch (InvocationTargetException e) {23. System.out.println("此处接收被调⽤⽅法内部未被捕获的异常");24. e.printStackTrace();25. } catch (InstantiationException e) {26. e.printStackTrace();27. }28. }29. }输出:1. 此处接收被调⽤⽅法内部未被捕获的异常2. ng.reflect.InvocationTargetException3. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)4. at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)5. at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)6. at ng.reflect.Method.invoke(Unknown Source)7. at com.zzj.test.reflect.Test.main(Test.java:11)8. Caused by: com.zzj.test.reflect.ZeroException: 参数不能⼩于零!9. at com.zzj.test.reflect.B.run(Reflect.java:13)10. at com.zzj.test.reflect.Reflect.run(Reflect.java:6)11. ... 5 more也可以直接打印⽬标异常:1. package com.zzj.test.reflect;2.3. import ng.reflect.InvocationTargetException;4. import ng.reflect.Method;5.6. public class Test {7. public static void main(String[] args) {8. try {9. Class<?> clazz = Class.forName("com.zzj.test.reflect.Reflect");10. Method method = clazz.getMethod("run", int.class);11. method.invoke(clazz.newInstance(), -1);12. } catch (ClassNotFoundException e) {13. e.printStackTrace();14. } catch (SecurityException e) {15. e.printStackTrace();16. } catch (NoSuchMethodException e) {17. e.printStackTrace();18. } catch (IllegalArgumentException e) {19. e.printStackTrace();20. } catch (IllegalAccessException e) {21. e.printStackTrace();22. } catch (InvocationTargetException e) {23. System.out.println("此处接收被调⽤⽅法内部未被捕获的异常");24. Throwable t = e.getTargetException();// 获取⽬标异常25. t.printStackTrace();26. } catch (InstantiationException e) {27. e.printStackTrace();28. }29. }30. }输出:1. 此处接收被调⽤⽅法内部未被捕获的异常2. com.zzj.test.reflect.ZeroException: 参数不能⼩于零!3. at com.zzj.test.reflect.B.run(Reflect.java:13)4. at com.zzj.test.reflect.Reflect.run(Reflect.java:6)5. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)6. at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)7. at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)8. at ng.reflect.Method.invoke(Unknown Source)9. at com.zzj.test.reflect.Test.main(Test.java:11)10.。

java.lang.reflect.InvocationTargetException

java.lang.reflect.InvocationTargetException

2013-12-16 15:48:03 org.apache.catalina.core.AprLifecycleListener init信息: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\javaTools\MyEclipse\Common\binary\com.sun.java.jdk.win32.x86_1.6.0.013\bin;D:\javaTools \Tomcat 6.0\apache-tomcat-6.0.14\bin2013-12-16 15:48:04 org.apache.coyote.http11.Http11Protocol init信息: Initializing Coyote HTTP/1.1 on http-80802013-12-16 15:48:04 org.apache.catalina.startup.Catalina load信息: Initialization processed in 1461 ms2013-12-16 15:48:04 org.apache.catalina.core.StandardService start信息: Starting service Catalina2013-12-16 15:48:04 org.apache.catalina.core.StandardEngine start信息: Starting Servlet Engine: Apache Tomcat/6.0.142013-12-16 15:48:05 org.apache.catalina.core.ApplicationContext log信息: ContextListener: contextInitialized()2013-12-16 15:48:05 org.apache.catalina.core.ApplicationContext log信息: SessionListener: contextInitialized()2013-12-16 15:48:05 org.apache.tomcat.util.digester.Digester endElement严重: End event threw exceptionng.reflect.InvocationTargetExceptionat sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at ng.reflect.Method.invoke(Method.java:597)at org.apache.tomcat.util.IntrospectionUtils.callMethodN(IntrospectionUtils.java:930)at org.apache.catalina.startup.CallMethodMultiRule.end(WebRuleSet.java:792)at org.apache.tomcat.util.digester.Rule.end(Rule.java:229)at org.apache.tomcat.util.digester.Digester.endElement(Digester.java:1058)at.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.ja va:601)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement( XMLDocumentFragmentScannerImpl.java:1774)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContent Driver.next(XMLDocumentFragmentScannerImpl.java:2930)at.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScanne rImpl.java:648)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(X MLDocumentFragmentScannerImpl.java:510)at.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.jav a:807)at.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.jav a:737)at .apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)at.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:120 5)at.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl. java:522)at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1562)at org.apache.catalina.startup.ContextConfig.applicationWebConfig(ContextConfig.java:369) at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:1062)at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:261)at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4239)at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)at org.apache.catalina.core.StandardService.start(StandardService.java:516)at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)at org.apache.catalina.startup.Catalina.start(Catalina.java:566)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at ng.reflect.Method.invoke(Method.java:597)at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)Caused by: ng.IllegalArgumentException: Servlet mapping specifies an unknown servlet name CoreServletat org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:2384)at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:2364) ... 45 more2013-12-16 15:48:05 org.apache.catalina.startup.ContextConfig applicationWebConfig严重: Parse error in application web.xml file at jndi:/localhost/Testweixin/WEB-INF/web.xml ng.IllegalArgumentException: Servlet mapping specifies an unknown servlet name CoreServletat org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2726)at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2752)at org.apache.tomcat.util.digester.Digester.endElement(Digester.java:1061)at.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.ja va:601)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement( XMLDocumentFragmentScannerImpl.java:1774)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContent Driver.next(XMLDocumentFragmentScannerImpl.java:2930)at.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScanne rImpl.java:648)at.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(X MLDocumentFragmentScannerImpl.java:510)at.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.jav a:807)at.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.jav a:737)at .apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)at.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:120 5)at.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl. java:522)at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1562)at org.apache.catalina.startup.ContextConfig.applicationWebConfig(ContextConfig.java:369) at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:1062)at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:261)at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4239)at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)at org.apache.catalina.core.StandardService.start(StandardService.java:516)at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)at org.apache.catalina.startup.Catalina.start(Catalina.java:566)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at ng.reflect.Method.invoke(Method.java:597)at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)2013-12-16 15:48:05 org.apache.catalina.startup.ContextConfig applicationWebConfig严重: Occurred at line 15 column 202013-12-16 15:48:05 org.apache.catalina.startup.ContextConfig start严重: Marking this application unavailable due to previous error(s)2013-12-16 15:48:05 org.apache.catalina.core.StandardContext start严重: Error getConfigured2013-12-16 15:48:05 org.apache.catalina.core.StandardContext start严重: Context [/Testweixin] startup failed due to previous errors2013-12-16 15:48:06 org.apache.coyote.http11.Http11Protocol start信息: Starting Coyote HTTP/1.1 on http-80802013-12-16 15:48:06 mon.ChannelSocket init信息: JK: ajp13 listening on /0.0.0.0:80092013-12-16 15:48:06 org.apache.jk.server.JkMain start信息: Jk running ID=0 time=0/31 config=null2013-12-16 15:48:06 org.apache.catalina.startup.Catalina start信息: Server startup in 2211 ms2013-12-16 15:54:06 org.apache.catalina.startup.HostConfig checkResources信息: Reloading context [/Testweixin]2013-12-16 15:54:06 org.apache.catalina.core.StandardContext stop信息: Container org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/Testweixin] has not been started<?xml version="1.0"encoding="UTF-8"?><web-app version="3.0"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_3_0.xsd"><servlet><servlet-name>coreServlet</servlet-name><servlet-class>org.liufeng.course.servlet.CoreServlet</serv let-class></servlet><servlet-mapping><servlet-name>C oreServlet</servlet-name><url-pattern>/coreServlet</url-pattern></servlet-mapping><display-name></display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>错误原因是,在配置servlet映射时,servlet-name中的名字写错了。

java反射机制性能优化

java反射机制性能优化

java反射机制性能优化import ng.reflect.InvocationTargetException;import ng.reflect.Method;import java.util.HashMap;import java.util.Map;import org.apache.log4j.Logger;public class DynamicServer {private static Logger log = Logger.getLogger(DynamicServer.class);public static Map<String,Class> clazzMap = new HashMap<String,Class>();public static Map<String,Object> objMap = new HashMap<String,Object>();public static Map<String,Method> metMap = new HashMap<String,Method>();public static Map<String,Map<String,String>> typeMap = new HashMap<String,Map<String,String>>();/*** 通过反射+缓存⾼效的调⽤某个类⾥⾯的某个⽅法* */public static Object cacheExce(String clazz,String method,Object[] os,Class[] cs) throws NoSuchMethodException{try {int size = 0;if(cs!=null){size = cs.length;}Method m = metMap.get(clazz+"_"+method+"_"+size);//⽤于区分重载的⽅法Object obj = objMap.get(clazz);if(m==null||obj==null){Class cl = clazzMap.get(clazz);if(cl==null){cl = Class.forName(clazz);clazzMap.put(clazz, cl);//缓存class对象}if(obj==null){obj = cl.newInstance();objMap.put(clazz, obj);//缓存对象的实例}if(m==null){m = cl.getMethod(method, cs);metMap.put(clazz+"_"+method+"_"+size, m);//缓存Method对象}}return m.invoke(obj , os);//动态调⽤某个对象中的public声明的⽅法} catch (Exception e) {e.printStackTrace();throw new NoSuchMethodException();}}/*** 通过反射+缓存获取指定类⾥⾯的指定⽅法的返回类型* */public static String cacheType(String clazz,String method) throws ClassNotFoundException{Map<String,String> clazzs = typeMap.get(clazz);if(clazzs==null){Map<String,String> mmap = new HashMap<String, String>();Class cl = Class.forName(clazz);Method[] ms = cl.getMethods();//获取某个类⾥⾯的所有的公共的⽅法for(Method m:ms){mmap.put(m.getName(), m.getGenericReturnType().toString());//遍历出所有的⽅法,将⽅法名和返回类型存在静态的map中(缓存)}clazzs = mmap;typeMap.put(clazz, mmap);}return clazzs.get(method);}}代码部分应该没啥要说的了吧,注释已经写的很清楚了,剩下的就需要参照jdk⽂档了。

Java:反射的常用用法,

Java:反射的常用用法,

Java:反射的常⽤⽤法,常⽤反射⽅法:package reflection;import java.io.IOException;import ng.reflect.InvocationTargetException;import ng.reflect.Method;import .URL;public class testReflection {public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String str="reflection.T";//获取类Class c=Class.forName(str);//获取类路径URL z=c.getResource("");URL s=c.getClassLoader().getResource("");//得到class在类中的地址ClassLoader d=c.getClassLoader();//得到class,c所实现的接⼝Class[] f=c.getInterfaces()[0];Class[] f=c.getInterfaces();System.out.println(z);System.out.println(s);System.out.println(d);System.out.println(f);//getClassLoader().getResource(fileName)//⽤获取到的类new⼀个新的对象Object o=c.newInstance();//接收该对象中所有的⽅法Method[] method = c.getMethods();System.out.println("此元素上的注释:"+c.getDeclaredAnnotations());for(Method m:method) {if(m.getName().equals("m")) {//⽅法选择第⼀个参数传递对象,后⾯的参数传递⽅法参数m.invoke(o);System.out.println("哈希码:"+m.hashCode());}if(m.getName().equals("b")) {m.invoke(o,1,2);//得到参数类型for(Class paramtype : m.getParameterTypes()) {System.out.println("参数类型:"+paramtype.getName());}}}}}/*//instanceof⽅法测试args返回的是否是⼀个class实例if(args[0] instanceof String)* @param args* */class T {public T(){System.out.println("构造函数被调⽤了");}public void m() {System.out.println("m函数被调⽤了");}public void b(int i,int j) {System.out.println("b函数的结果:"+i+j);}}⼀,利⽤反射⾃动为javabeen赋值例 been:package proxy;public class Notice{String type;String name;String data;String address;String vill;String upFile;String num;public String getName() {return name;}public void setName(String name) { = name;}public String getData() {return data;}public void setData(String data) {this.data = data;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getVill() {return vill;}public void setVill(String vill) {this.vill = vill;}public String getUpFile() {return upFile;}public void setUpFile(String upFile) {this.upFile = upFile;}public String getNum() {return num;}public void setNum(String num) {this.num = num;}public String getType() {return type;}public void setType(String type) {this.type = type;}}插⼊数据类:package cn.test;import ng.reflect.Field;import java.util.HashMap;public class ReflectDemo {static HashMap<String,String> data;static{data=new HashMap<String,String>();data.put("name","拟征收⼟地公告");data.put("type","测试公告");data.put("data","2017-01-12");data.put("address","成都市青⽺区");data.put("vill","⼆道街");data.put("upFile","⽂件具体的内容");data.put("num","⽂号:国:001");data.put("type","测试公告");}public static void main(String[] args)throws Exception { Notice obj=new Notice();test2(obj,data);System.out.println(obj.getAddress());}public static void test2(Notice obj,HashMap<String,String> data) throws Exception {Class cls=obj.getClass();//getDeclaredFields():获得某个类的所有声明的字段Field[] fields = cls.getDeclaredFields();for(Field field : fields){String item=data.get(field.getName());field.set(obj,item);}}}⼆,动态代理通过类实现InvocationHandler接⼝重写invoke⽅法实现可在需要调⽤的⽅法前⾯⾸先调⽤其他⽅法,做到权限控制实现类:package proxy;import ng.reflect.InvocationHandler;import ng.reflect.Method;import ng.reflect.Proxy;public class myProxyDemo implements InvocationHandler{Object aa;public Object newProxy(Object aa) {this.aa=aa;//返回⼀个指定接⼝的代理类实例(获取类加载地址,获取类实现的接⼝)return Proxy.newProxyInstance(aa.getClass().getClassLoader(),aa.getClass().getInterfaces(), this); }int count;public int count() {return count;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {befor(method,args);//调⽤此实例Object ad = method.invoke(this.aa,args);return null;} //可通过重写此⽅法完成不同功能public void befor(Method method, Object[] args){System.out.println("----------");}}测试类:public class TestProxy { //UserManager⼀个普通的javabeenpublic static void main(String[] args) {myProxyDemo handler=new myProxyDemo ();UserManager userManager=(UserManager) handler.newProxy(new UserManagerImpl());userManager.addUser("ad", "da");}}。

javassist用法asm用法以及区别

javassist用法asm用法以及区别

javassist⽤法asm⽤法以及区别======javassit ⽤法====== 在看dubbo源码和mybatis源码的时候发现代理⽤的是javassist,简单研究下。

可以动态的修改⼀个类,也可以动态的创建类,也可以实现代理(可以基于继承和接⼝两种)。

pom如下;<dependency><groupId>org.javassist</groupId><artifactId>javassist</artifactId><version>3.28.0-GA</version></dependency>1. 基本⽤法1. 实现动态的创建类和增加字段和⽅法package org.example.javassit;import javassist.*;import java.io.IOException;import ng.reflect.InvocationTargetException;import ng.reflect.Method;import .URISyntaxException;public class Test2 {public static void main(String[] args) throws Exception {test2();}// 动态的添加字段信息private static void test2() throws Exception {//创建类,这是⼀个单例对象ClassPool cp = ClassPool.getDefault();//我们需要构建的类CtClass ctClass = cp.get("cn.qz.Person");//创建字段,指定了字段类型、字段名称、字段所属的类CtField field = new CtField(cp.get("ng.Integer"), "age", ctClass);//指定该字段使⽤private修饰field.setModifiers(Modifier.PRIVATE);//设置age字段的getter/setter⽅法ctClass.addMethod(CtNewMethod.setter("getAge", field));ctClass.addMethod(CtNewMethod.getter("setAge", field));//当前⼯程的target⽬录final String targetClassPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();//⽣成.class⽂件ctClass.writeFile(targetClassPath);}// 创建类信息private static void test1() throws CannotCompileException, NotFoundException, URISyntaxException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodExcepti //创建类,这是⼀个单例对象ClassPool pool = ClassPool.getDefault();//我们需要构建的类CtClass ctClass = pool.makeClass("cn.qz.Person");//新增字段CtField field$name = new CtField(pool.get("ng.String"), "name", ctClass);//设置访问级别field$name.setModifiers(Modifier.PRIVATE);//也可以给个初始值ctClass.addField(field$name, CtField.Initializer.constant("qz-default"));//⽣成get/set⽅法ctClass.addMethod(CtNewMethod.setter("setName", field$name));ctClass.addMethod(CtNewMethod.getter("getName", field$name));//新增构造函数//⽆参构造函数CtConstructor cons$noParams = new CtConstructor(new CtClass[]{}, ctClass);cons$noParams.setBody("{name = \"qz\";}");ctClass.addConstructor(cons$noParams);//有参构造函数CtConstructor cons$oneParams = new CtConstructor(new CtClass[]{pool.get("ng.String")}, ctClass);// $0=this $1,$2,$3... 代表⽅法参数cons$oneParams.setBody("{$ = $1;}");ctClass.addConstructor(cons$oneParams);// 创建⼀个名为 print 的⽅法,⽆参数,⽆返回值,输出name值CtMethod ctMethod = new CtMethod(CtClass.voidType, "print", new CtClass[]{}, ctClass);ctMethod.setModifiers(Modifier.PUBLIC);ctMethod.setBody("{System.out.println(name);}");ctClass.addMethod(ctMethod);//当前⼯程的target⽬录final String targetClassPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();//⽣成.class⽂件ctClass.writeFile(targetClassPath);// 获取Class 对象的两种⽅式// 1. 直接转Class aClass = ctClass.toClass();// 2. 调⽤类加载获取 class 信息// Class<?> aClass = ClassLoader.getSystemClassLoader().loadClass("cn.qz.Person");Object o = aClass.newInstance();Method method = o.getClass().getMethod("print");method.invoke(o);}}2. 通过创建代理类实现增强:(1) 接⼝:package org.example.javassit.proxy;public interface IHelloService {String sayHello(String name);}(2) 代理接⼝package org.example.javassit.proxy;public interface IProxy {void setProxy(Object t);}(3) 测试类:package org.example.javassit.proxy;import javassist.*;import java.util.Arrays;/*** @author乔利强* @date 2021/8/31 10:45* @description*/public class ProxyTest {public static void main(String[] args) throws Exception {//创建类,这是⼀个单例对象ClassPool pool = ClassPool.getDefault();pool.appendClassPath(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath());//我们需要构建的类CtClass ctClass = pool.makeClass("org.example.javassit.proxy.HelloServiceJavassistProxy");//这个类实现了哪些接⼝ctClass.setInterfaces(new CtClass[]{pool.getCtClass("org.example.javassit.proxy.IHelloService"),pool.getCtClass("org.example.javassit.proxy.IProxy")});//新增字段CtField field$name = new CtField(pool.get("org.example.javassit.proxy.IHelloService"), "helloService", ctClass);//设置访问级别field$name.setModifiers(Modifier.PRIVATE);ctClass.addField(field$name);//新增构造函数//⽆参构造函数CtConstructor cons$noParams = new CtConstructor(new CtClass[]{}, ctClass);cons$noParams.setBody("{}");ctClass.addConstructor(cons$noParams);//重写sayHello⽅⽅法,可以通过构造字符串的形式CtMethod m = CtNewMethod.make(buildSayHello(), ctClass);ctClass.addMethod(m);// 创建⼀个名为 setProxy 的⽅法CtMethod ctMethod = new CtMethod(CtClass.voidType, "setProxy",new CtClass[]{pool.getCtClass("ng.Object")}, ctClass);ctMethod.setModifiers(Modifier.PUBLIC);//// $0=this $1,$2,$3... 代表⽅法参数ctMethod.setBody("{$0.helloService = $1;}");ctClass.addMethod(ctMethod);// 写到本地ctClass.writeFile(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath());//获取实例对象final Object instance = ctClass.toClass().newInstance();System.out.println(Arrays.toString(instance.getClass().getDeclaredMethods()));//设置⽬标⽅法if (instance instanceof IProxy) {IProxy proxy = (IProxy) instance;proxy.setProxy(new IHelloService() {@Overridepublic String sayHello(String name) {System.out.println("⽬标接⼝实现:name=" + name);return "name:" + name;}});}if (instance instanceof IHelloService) {IHelloService service = (IHelloService) instance;service.sayHello("qz");}}private static String buildSayHello() {String methodString = " public String sayHello(String name) {\n"+ " System.out.println(\"静态代理前 ..\");\n"+ " helloService.sayHello(name);\n"+ " System.out.println(\"静态代理后 ..\");\n"+ " return name;\n"+ " }";return methodString;}}结果:[public ng.String org.example.javassit.proxy.HelloServiceJavassistProxy.sayHello(ng.String), public void org.example.javassit.proxy.HelloServiceJavassistProxy.setProxy(java.静态代理前 ..⽬标接⼝实现:name=qz静态代理后 ..(4) 查看⽣成的类://// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//package org.example.javassit.proxy;public class HelloServiceJavassistProxy implements IHelloService, IProxy {private IHelloService helloService;public HelloServiceJavassistProxy() {}public String sayHello(String var1) {System.out.println("静态代理前 ..");this.helloService.sayHello(var1);System.out.println("静态代理后 ..");return var1;}public void setProxy(Object var1) {this.helloService = (IHelloService)var1;}}2. 实现代理1. 基于继承实现1. 需要增强的类:package org.example.javassit.proxy2;public class UserDao {public void saveUser() {System.out.println("saveUser ======-");}}2. ProxyFactory 实现增强(基于继承实现增强)package org.example.javassit.proxy2;import javassist.util.proxy.MethodFilter;import javassist.util.proxy.MethodHandler;import javassist.util.proxy.ProxyFactory;import ng.reflect.Method;public class ProxyTest {public static void main(String[] args) throws Exception {ProxyFactory factory = new ProxyFactory();// 设置写出的⽬录会导出到具体的⽬录// factory.writeDirectory = "D:/proxy";// 指定⽗类,ProxyFactory会动态⽣成继承该⽗类的⼦类factory.setSuperclass(UserDao.class);// 设定接⼝,接⼝可以继承多个,所以⽤数组// factory.setInterfaces(new Class[]{});//设置过滤器,判断哪些⽅法调⽤需要被拦截factory.setFilter(new MethodFilter() {@Overridepublic boolean isHandled(Method method) {if (method.getName().equals("saveUser")) {return true;}return false;}});//设置拦截处理factory.setHandler(new MethodHandler() {@Overridepublic Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { System.out.println("前置处理");Object result = proceed.invoke(self, args);System.out.println("执⾏结果:" + result);System.out.println("后置处理");return result;}});// 创建 UserDao 代理类,并创建代理对象Class<?> c = factory.createClass();UserDao javassistTest = (UserDao) c.newInstance();// saveUser⽅法,会被拦截javassistTest.saveUser();System.out.println(javassistTest.toString());}}结果:前置处理saveUser ======-执⾏结果:null后置处理erDao_$$_jvst840_0@1593948d3. 反编译查看类//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//package org.example.javassit.proxy2;import java.io.ObjectStreamException;import ng.reflect.Method;import javassist.util.proxy.MethodHandler;import javassist.util.proxy.ProxyObject;import javassist.util.proxy.RuntimeSupport;public class UserDao_$$_jvst840_0 extends UserDao implements ProxyObject {public static MethodHandler default_interceptor;private MethodHandler handler;public static byte[] _filter_signature;public static final long serialVersionUID;private static Method[] _methods_;public UserDao_$$_jvst840_0() {this.handler = default_interceptor;if (default_interceptor == null) {this.handler = RuntimeSupport.default_interceptor;}super();}public final void _d7saveUser() {super.saveUser();}public final void saveUser() {Method[] var1 = _methods_;this.handler.invoke(this, var1[14], var1[15], new Object[0]);}static {Method[] var0 = new Method[24];Class var1 = Class.forName("erDao_$$_jvst840_0");RuntimeSupport.find2Methods(var1, "saveUser", "_d7saveUser", 14, "()V", var0);_methods_ = var0;serialVersionUID = -1L;}public void setHandler(MethodHandler var1) {this.handler = var1;}public MethodHandler getHandler() {return this.handler;}Object writeReplace() throws ObjectStreamException {return RuntimeSupport.makeSerializedProxy(this);}}2. 基于接⼝(1) UserDao 接⼝package org.example.javassit.proxy2;public interface UserDao {void saveUser();}(2) 测试类:package org.example.javassit.proxy2;import javassist.util.proxy.MethodFilter;import javassist.util.proxy.MethodHandler;import javassist.util.proxy.ProxyFactory;import ng.reflect.Method;import java.util.Arrays;public class ProxyTest {public static void main(String[] args) throws Exception {ProxyFactory factory = new ProxyFactory();// 设置写出的⽬录会导出到具体的⽬录factory.writeDirectory = "D:/proxy";// 设定接⼝,接⼝可以继承多个,所以⽤数组factory.setInterfaces(new Class[]{UserDao.class});//设置过滤器,判断哪些⽅法调⽤需要被拦截factory.setFilter(new MethodFilter() {@Overridepublic boolean isHandled(Method method) {if (method.getName().equals("saveUser")) {return true;}return false;}});//设置拦截处理factory.setHandler(new MethodHandler() {@Overridepublic Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {System.out.println("前置处理");System.out.println("self: " + self + "\tthisMethod: " + thisMethod + "\tproceed: " + proceed + "\targs: " + Arrays.toString(args));System.out.println("后置处理");return "";}});// 创建 UserDao 代理类,并创建代理对象Class<?> c = factory.createClass();UserDao javassistTest = (UserDao) c.newInstance();// saveUser⽅法,会被拦截javassistTest.saveUser();System.out.println(javassistTest.toString());}}(3) 结果;前置处理self: erDao_$$_jvst840_0@1b604f19 thisMethod: public abstract void erDao.saveUser() proceed: null args: []后置处理erDao_$$_jvst840_0@1b604f19(4) 反编译查看类//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//package org.example.javassit.proxy2;import java.io.ObjectStreamException;import ng.reflect.Method;import javassist.util.proxy.MethodHandler;import javassist.util.proxy.ProxyObject;import javassist.util.proxy.RuntimeSupport;public class UserDao_$$_jvst840_0 implements UserDao, ProxyObject {public static MethodHandler default_interceptor;private MethodHandler handler;public static byte[] _filter_signature;public static final long serialVersionUID;private static Method[] _methods_;public UserDao_$$_jvst840_0() {this.handler = default_interceptor;if (default_interceptor == null) {this.handler = RuntimeSupport.default_interceptor;}super();}public final void saveUser() {Method[] var1 = _methods_;this.handler.invoke(this, var1[14], var1[15], new Object[0]);}static {Method[] var0 = new Method[24];Class var1 = Class.forName("erDao_$$_jvst840_0");RuntimeSupport.find2Methods(var1, "saveUser", (String)null, 14, "()V", var0);_methods_ = var0;serialVersionUID = -1L;}public void setHandler(MethodHandler var1) {this.handler = var1;}public MethodHandler getHandler() {return this.handler;}Object writeReplace() throws ObjectStreamException {return RuntimeSupport.makeSerializedProxy(this);}}==========asm ⽤法========== javassit 主要类似于⽤java源码加反射的机制实现改变⼀些操作。

解决spring@ControllerAdvice处理异常无法正确匹配自定义异常

解决spring@ControllerAdvice处理异常无法正确匹配自定义异常

解决spring@ControllerAdvice处理异常⽆法正确匹配⾃定义异常⾸先说结论,使⽤@ControllerAdvice配合@ExceptionHandler处理全局controller的异常时,如果想要正确匹配⾃⼰的⾃定义异常,需要在controller的⽅法上抛出相应的⾃定义异常,或者⾃定义异常继承RuntimeException类。

问题描述:1、在使⽤@ControllerAdvice配合@ExceptionHandler处理全局异常时,⾃定义了⼀个AppException(extends Exception),由于有些全局的参数需要统⼀验证,所以在所有controller的⽅法上加⼀层AOP校验,如果参数校验没通过也抛出AppException2、在@ControllerAdvice标记的类上,主要有两个@ExceptionHandler,分别匹配AppException.class和Throwable.class。

3、在测试时,由于全局AOP的参数校验没通过,抛出了AppException,但是发现这个AppException被Throwable.class匹配到了,⽽不是我们想要的AppException.class匹配上。

分析过程:⼀阶段开始由于⼀直测试的两个不同的请求(⼀个通过swagger,⼀个通过游览器地址输⼊,两个请求⽐较相似,我以为是同⼀个请求),⼀个⽅法上抛出了AppException,⼀个没有,然后发现这个问题时现时不现,因为⽆法稳定复现问题,我猜测可能是AppException出了问题,所以我修改了AppException,将其⽗类改为了RuntimeException,然后发现问题解决了⼆阶段问题解决后,我⼜思考了下为啥会出现这种情况,根据java的异常体系来说,⽆论是继承Exception还是RuntimeException,都不应该会匹配到Throwable.class上去。

JavaBean对象与Map对象互相转化

JavaBean对象与Map对象互相转化

JavaBean对象与Map对象互相转化package testExcelFile;import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import ng.reflect.InvocationTargetException;import ng.reflect.Method;import java.util.HashMap;import java.util.Map;public class BeanToMapUtil {/*** 将⼀个 Map 对象转化为⼀个 JavaBean** @param type* 要转化的类型* @param map* 包含属性值的 map* @return 转化出来的 JavaBean 对象* @throws IntrospectionException* 如果分析类属性失败* @throws IllegalAccessException* 如果实例化 JavaBean 失败* @throws InstantiationException* 如果实例化 JavaBean 失败* @throws InvocationTargetException* 如果调⽤属性的 setter ⽅法失败*/public static Object convertMap(Class type, Map map)throws IntrospectionException, IllegalAccessException,InstantiationException, InvocationTargetException {BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性Object obj = type.newInstance(); // 创建 JavaBean 对象// 给 JavaBean 对象的属性赋值PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (int i = 0; i < propertyDescriptors.length; i++) {PropertyDescriptor descriptor = propertyDescriptors[i];String propertyName = descriptor.getName();if (map.containsKey(propertyName)) {// 下⾯⼀句可以 try 起来,这样当⼀个属性赋值失败的时候就不会影响其他属性赋值。

JavaJDK动态代理的基本原理详细介绍

JavaJDK动态代理的基本原理详细介绍

JavaJDK动态代理的基本原理详细介绍JDK动态代理详解本⽂主要介绍JDK动态代理的基本原理,让⼤家更深刻的理解JDK Proxy,知其然知其所以然。

明⽩JDK动态代理真正的原理及其⽣成的过程,我们以后写JDK Proxy可以不⽤去查demo,就可以徒⼿写个完美的Proxy。

下⾯⾸先来个简单的Demo,后续的分析过程都依赖这个Demo去介绍,例⼦采⽤JDK1.8运⾏。

JDK Proxy HelloWorldpackage com.yao.proxy;/*** Created by robin*/public interface Helloworld {void sayHello();}package com.yao.proxy;import com.yao.HelloWorld;/*** Created by robin*/public class HelloworldImpl implements HelloWorld {public void sayHello() {System.out.print("hello world");}}package com.yao.proxy;import ng.reflect.InvocationHandler;import ng.reflect.Method;/*** Created by robin*/public class MyInvocationHandler implements InvocationHandler{private Object target;public MyInvocationHandler(Object target) {this.target=target;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("method :"+ method.getName()+" is invoked!");return method.invoke(target,args);}}package com.yao.proxy;import com.yao.HelloWorld;import ng.reflect.Constructor;import ng.reflect.InvocationHandler;import ng.reflect.InvocationTargetException;import ng.reflect.Proxy;/*** Created by robin*/public class JDKProxyTest {public static void main(String[]args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//这⾥有两种写法,我们采⽤略微复杂的⼀种写法,这样更有助于⼤家理解。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

ng.reflect.InvocationTargetException的一
个可能原因
这几天项目正在不断测试、演示中,当我把项目交给测试和实施部的时候项目一切运行正常,可是昨天一实施人员告诉我,系统部署到tomcat中启动运行报出了一个异常,发给我看了一下,我的个乖乖,这个异常信息这么久我还是头一次看见,于是赶紧的上网查了一下资料,后来通过各种测试,环境搭建模拟发现产生该异常信息的主要原因可能是一下几点:
1、包冲突、有重复包或者缺少包
2、项目jdk和部署jdk版本不一样,导致InvocationTargetException异常信息返回一个空值,没有调用invoc里的重写消息方法。

3、映射文件发生改变
对于不同原因的解决:
1、包:直接自己挨着查看就是了,但是一定要注意遇到重复包的时候你的系统究竟需要哪一个版本
2、jdk版本:
⑴、更换jdk包
⑴、用一个方法统一处理该异常
private static void handleException(Exception e){
String msg=null;
if(e instanceof InvocationTargetException){
Throwable targetEx=((InvocationTargetException)e).getTargetException();
if(targetEx t!=null){
msg=targetEx.getMessage();
}
}else{
msg=e.getMessage();
}
MessageDialong.openError(Activator.getDetDefault().getWorkbench().getDisplay().getActiveshell (),"error",msg);
e.printStackTrace();
}
3、映射文件发生改变
在项目中有的地方是使用反射机制进行的操作,可能对于类进行了某些更改,科室映射文件没有更改,采用匿名就会出现这样的问题,解决办法要么更改映射文件,要不不要使用匿名调用。

相关文档
最新文档