/* Why Mother Didn't Teach You Everything About Java Either ... Sequel By Chuck Liang Mother: What kind of program are you working on, and what programming language are you using, sweetheart? Man: I'm using Java now, just like you said I should. I'm writing a program that keeps track of bank accounts. And I'm making all my instance variables PRIVATE. Your balance is safe with me! Mother: Uh oh, I was afraid this was going to happen ... There's something I never told you about Java. Man: What? Not again! You promised! What didn't you tell me about Java? Mother: That there's a package called reflection which will give you access to all private elements of a class, and even list them for you. Man: Motherhacker! What the hell! That's terrible! Why bother! Why didn't you tell me the truth?! Mother: Private variables and methods are designed for encapsulation, not for security. But I had to invent a story that was easy for you to believe, like when I told you that santa claus won't come to our house unless you ate your vegetables. Mother: But perhaps this notion of privacy represents a naive understanding of the kind of program organization that's required of modern software. Sometimes we require the flexibility of changing the abstraction ... Man: What are you talking about ma? That there's no santa claus? Mother: Of course there is! Just eat your vegetables. */ import java.lang.reflect.*; class account { private double balance; ///// PRIVATE VARS CAN'T BE SEEN BY BAD PEOPLE?! public account(double b) { balance=b; } public void withdraw(double amt) { if (amt>0 && amt1000000 && Math.random()<.000000000001) //the rich get richer winprize(); // you won you lucky hacker! } public double inquiry() { return balance; } private void winprize() { balance += 10000; } // only call internally! }//account public class mother { public static void main(String[] argv) throws Exception { account youraccount = new account(1000); Field bal = account.class.getDeclaredField("balance"); bal.setAccessible(true); double yourbalance = bal.getDouble(youraccount); System.out.println("your 'private' balance was "+yourbalance); bal.setDouble(youraccount,0); // balance set to 0. Motherhacker! System.out.println("but now it is "+youraccount.inquiry()); // what kind of "private" methods sucker bank won't allow me to call? Method[] F = account.class.getDeclaredMethods(); System.out.println("all methods of account class:"); for(Method m:F) {System.out.println(m.getName());} Method alwayswin = account.class.getDeclaredMethod("winprize"); alwayswin.setAccessible(true); for(int i=0;i<100;i++) alwayswin.invoke(youraccount); System.out.println("But you're extremely lucky and your balance is now "+youraccount.inquiry()); }//main }