防止其他类的类实例化 [英] Preventing class instantiation from other classes

查看:82
本文介绍了防止其他类的类实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用域,视图和控制器.每个都包含自己的类.

I'm working with a domain, view and controllers. Each containing their own classes.

域包含许多不应在域外的类中实例化的类.我的印象是默认访问修饰符将为我提供帮助.使我的域类的构造函数包可见.

The domain contains a lot of classes that should not be instantiated in classes outside of the domain. I was under the impression the default access modifier was going to help me. Making my domain classes their constructors package visible.

结果证明,导入正确的package.class文件后,任何类仍可以使用构造函数.

Turns out any class can still use the constructors after importing the right package.class file.

如何防止这种情况发生?

How can I prevent this from happening?

推荐答案

当您说结果是,导入正确的package.class文件后,任何类仍然可以使用构造函数."我猜你在谈论反思. 反射是一个强大的概念,即使类仅提供私有构造函数,它也允许任意实例化类. 无法阻止某人使用反射来实例化您的类.可以使用反射来绕过诸如私有或保护之类的类或构造函数修饰符.

When you say 'Turns out any class can still use the constructors after importing the right package.class file.' I guess you are talking about Reflection. Reflection is a powerful concept allowing arbitrary instantiation of classes even if they only provide a private constructor. There is no way to prevent someone from using reflection to instantiate your classes. The class or constructor modifiers such as private or protected can be bypassed using reflection.

这篇关于防止其他类的类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆