在《Thingking in Java》一书中,关于“类的访问权限”有一句很不起眼的话:“如果你没能为类访问权限指定一个访问修饰符,它就会缺省得到包访问权限。这意味着该类的对象可以由包内任何其他类来创建,但在包外则不行。然后,如果该类的某个static成员是public的话,则客户端程序员仍旧可以调用该static成员,哪怕是他们并不能生成该类的对象。”对这句话的后面一段想了很久,都想不出一个合适的例子:就是如何通过包外的类调用包内的“包访问权限”的类中public static 成员。
调试欢乐多
Note that a class cannot be private (that would make it inaccessible to anyone but the class) or
protected.6 So you have only two choices for class access: package access or public. If you don’t
want anyone else to have access to that class, you can make all the constructors private, thereby
preventing anyone but you, inside a static member of the class, from creating an object of that
class. Here’s an example:
//: access/Lunch.java
// Demonstrates class access specifiers. Make a class
// effectively private with private constructors:
class Soup1 {
private Soup1() {}
// (1) Allow creation via static method:
public static Soup1 makeSoup() {
return new Soup1();
}
}
package com.csdn.yaoguicheng.exampleclass packageExample{ private static packageExample instance = new packageExample(); private packageExample(){}
public static getPackageExampleInstance(){
return instance;
}}package com.csdn.yaoguicheng.example2import com.csdn.yaoguicheng.*;
class example2{
private packageExample pe = packageExample.getPackageExampleInstance();
public example2(){}
}
//class example2就是通过包外的类调用包内的“包访问权限”的packageExample类中public static 成员getPackageExampleInstance。
3楼写的其实是个单例模式,LZ说编译通不过?
看看。。把这句改下
public static packageExample getPackageExampleInstance()
可以了吧
你还可以在测试类中测试下每次返回的是否都是同一对象
你没理解楼主的意思,楼主的意思是因为包着public static方法的类是对其他包不可见的,那么在其他包里应该没有办法去调用这个public static 方法
而且我个人觉得似乎没有办法用到吧
package com.haojia.test;class T {
public static void go() {
System.out.println("success!");
}
}package com.haojia.test2;import java.lang.reflect.Method;public class T2 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("com.haojia.test.T");
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().equals("go")) {
m[i].setAccessible(true);
m[i].invoke(null);
}
}
}
}
public static void main(String[] args) throws Exception {
Method m = Class.forName("com.haojia.test.T").getDeclaredMethod("go");
m.setAccessible(true);
m.invoke(null);
}
}