加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:28:04 所属栏目:大数据 来源:网络整理
导读:我在Spring Controller中使用内部类.从它的父类超类访问受保护的字段/方法时遇到问题. 研究表明,这是由不同的类加载器在某种程度上造成的,但我不太了解Spring确定. class SuperBaseController { protected String aField; protected void aMethod() { }}@Con

我在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中,我使用了以下配置:


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

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

我希望它有用

安杰洛

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读