Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

Can we access private data outside of the class directly in
java programming language? Why There is no runtime checking
in java, which leads to access the private data directly
outside of a class?

Answer Posted / gaurav sehra

Using reflection we can see\access private data or private method of a class
u can try the below code and will easily see the desired result :-

import java.lang.reflect.Field;
class SimpleKeyPair {
private String privateKey = "India"; // private field
}
public class PrivateMemberAccessTest {
public static void main(String[] args) throws Exception {
SimpleKeyPair keyPair = new SimpleKeyPair();
Class c = keyPair.getClass();

// get the reflected object
Field field = c.getDeclaredField("privateKey");
// set accessible true
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Tokyo"
// modify the member varaible
field.set(keyPair, "Bharat");
System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Berlin"
}
}

Is This Answer Correct ?    7 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is canonical name in java?

1062


What are conditionals and its types?

1084


Is null a string in java?

1012


Why string is immutable with example?

917


Which graphs are functions?

912


What is this keyword used for?

1075


Given a singly linked list, determine whether it contains a loop or not without using temporary space?

941


Difference between final and effectively final ?

1030


Is main an identifier?

954


What about interthread communication and how it takes place in java?

998


Which arithmetic operations can result in the throwing of an arithmeticexception?

977


Can a class have multiple constructors?

965


Write a java program to generate fibonacci series ?

1024


What are thread local variables?

1065


Tell some latest versions in JAVA related areas?

934