ch11: sample code
This commit is contained in:
8
11-pythonic-obj/private/Confidential.java
Normal file
8
11-pythonic-obj/private/Confidential.java
Normal file
@@ -0,0 +1,8 @@
|
||||
public class Confidential {
|
||||
|
||||
private String secret = "";
|
||||
|
||||
public Confidential(String text) {
|
||||
secret = text.toUpperCase();
|
||||
}
|
||||
}
|
||||
25
11-pythonic-obj/private/Expose.java
Normal file
25
11-pythonic-obj/private/Expose.java
Normal file
@@ -0,0 +1,25 @@
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
public class Expose {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Confidential message = new Confidential("top secret text");
|
||||
Field secretField = null;
|
||||
try {
|
||||
secretField = Confidential.class.getDeclaredField("secret");
|
||||
}
|
||||
catch (NoSuchFieldException e) {
|
||||
System.err.println(e);
|
||||
System.exit(1);
|
||||
}
|
||||
secretField.setAccessible(true); // break the lock!
|
||||
try {
|
||||
String wasHidden = (String) secretField.get(message);
|
||||
System.out.println("message.secret = " + wasHidden);
|
||||
}
|
||||
catch (IllegalAccessException e) {
|
||||
// this will not happen after setAcessible(true)
|
||||
System.err.println(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
6
11-pythonic-obj/private/expose.py
Normal file
6
11-pythonic-obj/private/expose.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import Confidential
|
||||
|
||||
message = Confidential('top secret text')
|
||||
secret_field = Confidential.getDeclaredField('secret')
|
||||
secret_field.setAccessible(True) # break the lock!
|
||||
print 'message.secret =', secret_field.get(message)
|
||||
11
11-pythonic-obj/private/leakprivate.py
Normal file
11
11-pythonic-obj/private/leakprivate.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from java.lang.reflect import Modifier
|
||||
import Confidential
|
||||
|
||||
message = Confidential('top secret text')
|
||||
fields = Confidential.getDeclaredFields()
|
||||
for field in fields:
|
||||
# list private fields only
|
||||
if Modifier.isPrivate(field.getModifiers()):
|
||||
field.setAccessible(True) # break the lock
|
||||
print 'field:', field
|
||||
print '\t', field.getName(), '=', field.get(message)
|
||||
17
11-pythonic-obj/private/no_respect.py
Normal file
17
11-pythonic-obj/private/no_respect.py
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
"""
|
||||
In the Jython registry file there is this line:
|
||||
|
||||
python.security.respectJavaAccessibility = true
|
||||
|
||||
Set this to false and Jython provides access to non-public
|
||||
fields, methods, and constructors of Java objects.
|
||||
"""
|
||||
|
||||
import Confidential
|
||||
|
||||
message = Confidential('top secret text')
|
||||
for name in dir(message):
|
||||
attr = getattr(message, name)
|
||||
if not callable(attr): # non-methods only
|
||||
print name + '\t=', attr
|
||||
Reference in New Issue
Block a user