private安全性 把一个方法或者变量声明成private,一定安全么?求解释。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 private 是安全的!前面有人说用反射可以读取,那是因为没有对 Java 进行安全策略文件的限制! 这在C++里通过破坏类的安全机制取得类地址就可以。但在java里没有指针,我想不出怎样不通过成员函数取得private成员的值的方法。请高手给个反例。另外,楼主,访问权限是为了帮助你管理好你的模块,如果你硬要访问,都设为public也未偿不可。规则的制定不是为了让你违反的。 反射:import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(value = RetentionPolicy.RUNTIME)public @interface Value{ String[] value();}public class Test01{ //私有属性 private int a = 0; //私有方法 @Value(value = { "hello", "world" }) private int add(int b) { return a + b; }}import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test02{ public static void main(String[] args) throws Exception { // Class cls = Test01.class; 或者 Test01 tst = new Test01(); Class cls = Class.forName("Test01"); // 反射设置属性 Field field = cls.getDeclaredField("a"); field.setAccessible(true); //更改为可访问 field.setInt(tst, 10); // 反射调用方法 Method method = cls.getDeclaredMethod("add", int.class); method.setAccessible(true); //更改为可访问 int rst = (Integer) method.invoke(tst, 8); System.out.println(rst); // 反射取得方法的注解 Annotation[] anns = method.getAnnotations(); for (Annotation a : anns) { if (a instanceof Value) { String[] strs = ((Value) a).value(); System.out.println(strs[0] + "$" + strs[1]); } } }} 关于Swing的标签排版 如何卸载Java 帮我看一下这些代码是什么意思 麻烦推存JAVA书籍 rmi中的编译问题 swing的JFileChooser组件可否控制字体? 急:请教高手一个算法 谁有王森的《java 深度历险》的电子文档 急!怎么让在命令行输出的东东实现左对齐,居中等呢? 关于SCOKET和线程,急!!! 深度复制 在线等!servlet的问题,懂的人肯定觉得很简单!!
规则的制定不是为了让你违反的。
import java.lang.annotation.RetentionPolicy;@Retention(value = RetentionPolicy.RUNTIME)
public @interface Value
{
String[] value();
}public class Test01
{
//私有属性
private int a = 0; //私有方法
@Value(value = { "hello", "world" })
private int add(int b)
{
return a + b;
}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;public class Test02
{
public static void main(String[] args) throws Exception
{
// Class cls = Test01.class; 或者
Test01 tst = new Test01();
Class cls = Class.forName("Test01"); // 反射设置属性
Field field = cls.getDeclaredField("a");
field.setAccessible(true); //更改为可访问
field.setInt(tst, 10); // 反射调用方法
Method method = cls.getDeclaredMethod("add", int.class);
method.setAccessible(true); //更改为可访问
int rst = (Integer) method.invoke(tst, 8);
System.out.println(rst); // 反射取得方法的注解
Annotation[] anns = method.getAnnotations();
for (Annotation a : anns)
{
if (a instanceof Value)
{
String[] strs = ((Value) a).value();
System.out.println(strs[0] + "$" + strs[1]);
}
} }
}