Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.sun.proxy.$Proxy0.toString()

I am using JDKProxy to implement mybatis, but I have a question

I have no code with proxy.toString()

public class BootStrap {
    public static void start(){
        MySqlSession sqlSession = new MySqlSession();
        TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
        Test test = testMapper.selectByPrimaryKey(2);
    }

    public static void main(String[] args){
        start();
    }
}
@Data
public class MySqlSession {
    public <T> T getMapper(Class<T> clazz){
        return (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),//类加载器
                new Class[]{clazz},//接口
                new MapperProxy(this));//代理类
    }

    public <T> T selectByPrimaryKey(MapperData mapperData, Object parameter){
        return executor.query(mapperData,parameter);
    }
}
//it is no "proxy.toString" 
//the bug is in this method
public class MapperProxy<T> implements InvocationHandler {

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            int seperate = method.getDeclaringClass().getName().lastIndexOf(".");
            String mapper = method.getDeclaringClass().getName().substring(seperate + 1);
            MapperData mapperData =
                    sqlSession.getConfiguration()
                            .getMapperRegistory()
                            .get(mapper + "." + method.getName());
            if(null != mapperData){
                System.out.println(String.format("SQL [%s],parameter [%s]", mapperData.getSql(), args[0]));
                Class<?> clazz = sqlSession.getClass();
                Method realMethod = clazz.getMethod(method.getName(), new Class[]{MapperData.class, Object.class});
                return realMethod.invoke(sqlSession,mapperData,args);
            }
            return method.invoke(sqlSession,args);
        }catch (InvocationTargetException ite) {
            throw ite.getCause();
        }
    }
}

If I run return method.invoke(sqlSession,args);, this bug disappear,so I think the bug is in this method

like image 937
dc p Avatar asked Jul 06 '26 15:07

dc p


1 Answers

lombok generates the toString method automatically for u

u can check documentation of the annotation

@Data

Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor. Equivalent to @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.

like image 92
Jian Avatar answered Jul 09 '26 07:07

Jian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!