Search code examples
javareflectioncompiler-constructionjvm

jit compiler vs reflection


While studying these two keywords, there is a part where I get confused.

The jit compiler interprets or compiles instructions dynamically, that is, line-by-line.

I learned that reflection is necessary in order to run dynamically since Java is a static language.

I don't know the functional difference between the two. The jit compiler interprets and compiles dynamically, but isn't this act of finding out information such as class type dynamically?


Solution

  • First there are some incorrect statements in your question.

    The JIT compiler interprets or compiles instructions dynamically, that is, line-by-line.

    That is incorrect:

    1. The JIT compiler compiles code from bytecodes to native code. It doesn't interpret code.

    2. It does it "just in time" (at runtime). Dynamic is a possible adverb, but it kind of misses the point. (JIT compilation typically happens just once ...)

    3. JIT compilation does not happen "line by line". The granularity of JIT compilation is an entire method.

    Also JIT compilation is transparent to the program. It doesn't change how the program behaves ... apart from making it go faster.

    I learned that reflection is necessary in order to run dynamically since Java is a static language.

    That is also incorrect. Java is dynamic in many respects without reflection. For example, the Java language supports:

    • dynamic typing using type casts, instanceof
    • dynamic method call dispatching
    • dynamic binding via the standard classloaders

    and so on.

    Reflection allows you to do certain dynamic things that are not practical using conventional Java compiled from (static) source code. But saying that reflection is necessary to do "dynamic" things in Java is incorrect (or circular).


    In reality, reflection and JIT are unrelated:

    • JIT is a technology for implementing the Java language. It doesn't alter the nature of the language, or what you can do with it. It is NOT about "dynamic" behavior at all. Furthermore, it is not a requirement that a Java implementation includes a JIT compiler, and indeed some implementations don't.

    • Reflection is a fundamental part of the standard Java class library. It allows you to do certain "dynamic" things that would be difficult to do with the core Java language. And it certainly affects the behavior of Java programs.


    Finally, you will observe that "dynamic" has a wide range of meanings in different contexts. You need to careful not to conflate the meanings across the contexts. (Which is not an easy thing for people whose first language is not English ...)