How is the type of a field stored in java? Sorry if I am saying this wrong. I will give a example. int x = 4 Where is the fact that x is in an int stored and how do I access the information that says x is an int?
An int has been 4 bytes long. When you declare a variable an int, 4 bytes are allocated for it. As 64 bit machines become more prevalent, int will probably become 8 bytes.
When the Java compiler generates the .class file containing the compiled byte codes corresponding to the Java class that contains your code, the fact that x is an int is stored in the .class file. int will *never* become an 8-byte number, because it is defined as a 32-bit signed integer in the Java Language Specification. Whether it is stored as 64 bits depends on the implementation of the Java Runtime Environment. 64-bit signed integers are called "long". You use the methods in java.lang.reflect to find the type of a declared field, but the accessibility of that information is limited to the visibility of the declared variable; for instance, you can only see the type of a declared variable from a class that is not in the same package if the variable is declared "public." See http://docs.oracle.com/javase/tutorial/reflect/index.html .
If I wanted to make my own getType method how would I access the information on the field's type from the .class file. I am really new to java and programming in general so sorry if this is a stupid question or one that is to hard to answer. I want to try and make something like python's Type(variable) thing.
String myFieldClassName = myObject.getClass().getDeclaredField("myFieldName").getType().getName(); //See the javadoc for these methods beginning with java.lang.Object.getClass()
Join our real-time social learning platform and learn together with your friends!