java – 当内部类访问受保护的外部类超级时,如何避免“IllegalAccessError”

我在Spring Controller中使用内部类.从它的父类超类访问受保护的字段/方法时遇到问题.

研究表明,这是由不同的类加载器在某种程度上造成的,但我不太了解Spring确定.

class SuperBaseController {
    protected String aField;

    protected void aMethod() {

    }
}

@Controller
class OuterMyController extends SuperBaseController {

    class Inner {

        public void itsMethod() {
            // java.lang.IllegalAccessError: tried to access method
            aMethod();
        }

        public void getField() {
            // java.lang.IllegalAccessError: tried to access field
            String s = aField;
        }
    }

    void doSomething () {
        // ObvIoUsly fine.
        aMethod();
        // Fails in the Inner method call.
        new Inner().itsMethod();

        // ObvIoUsly fine.
        String s = aField;
        // Fails in the Inner method call.
        new Inner().getField();
    }
}

有没有简单的技术来避免/解决这个问题?优选地,不涉及使字段/方法公开.

我已经确认外部类的ClassLoader属性与超类的ClassLoader属性不同.

最佳答案
我创建了以下类:

public class BaseController
{
    protected String field;
    protected void method()
    {
        System.out.println("I'm protected method");
    }
}

@RestController
@RequestMapping("/stack")
public class StackController extends BaseController
{
    class Inner
    {
        public void methodInvocation()
        {
            method();
        }
        public void fieldInvocation()
        {
            field = "Test";
        }
    }
    @RequestMapping(value= {"/invoca"},method= {RequestMethod.GET})
    public ResponseEntity

我试图调用其他服务,我没有问题.现在我将这个配置用于Spring(基于注释的注释):

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "it.spring.controller" })
@PropertySource( value={"classpath:config.properties"},encoding="UTF-8",ignoreResourceNotFound=false)
public class DbConfig
{
}


@Configuration
@EnableWebMvc
@Import(DbConfig.class)
@PropertySource(value = { "classpath:config.properties" },encoding = "UTF-8",ignoreResourceNotFound = false)
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
}

如您所见,我使用了@Import注释,在我的web.xml中,我使用了以下配置:

dispSvltdispatcherServletaram>
        aram-name>contextClassaram-name>
        aram-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContextaram-value>
    aram>
    aram>
        aram-name>contextConfigLocationaram-name>
        aram-value>it.WebMvcConfigaram-value>
    aram>
    aram>
        aram-name>dispatchOptionsRequestaram-name>
        aram-value>truearam-value>
    aram>
    

通过使用此配置,我在调用内部类中的受保护字段和/或方法时没有任何问题

如果你无法使你的配置适应这个..你可以发布你使用的配置吗?

我希望它有用

安杰洛

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...