Disabling compile-time dependency checking when compiling Java classes

后端 未结 8 1140
一整个雨季
一整个雨季 2020-12-28 09:10

Consider the following two Java classes:

a.) class Test { void foo(Object foobar) { } }

b.) class Test { void foo(pkg.not.in.classpath.FooBar foobar) { } }
         


        
8条回答
  •  隐瞒了意图╮
    2020-12-28 09:31

    I can't see how you could allow this without breaking java type checking. How would you use your referenced object in your method? To extend on your example,

    class test {
       void foo (pkg.not.in.classpath.FooBar foobar) { 
           foobar.foobarMethod(); //what does the compiler do here?
      } 
    }
    

    If you're in some situation where you've got to compile (and call a method ) on something that works on a library you don't have access to the closest you can come is to get the method via reflection, something like (method calls from memory, may be inaccurate)

     void foo(Object suspectedFoobar)
         {
           try{
            Method m = suspectedFoobar.getClass().getMethod("foobarMethod");
            m.invoke(suspectedFoobar);
           }
           ...
         }
    

    I can't really see the point of doing this, though. Can you provide more information on the problem you're trying to solve?

提交回复
热议问题