Renaming openconnection() or cutting it up?

后端 未结 2 727
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 09:23

Is it possible to rename the openconnection()?

Orginal:

URL url = new URL(\"http://google.co.in\");
URLConnection connection = url.**openConnection**();
         


        
2条回答
  •  执念已碎
    2021-01-27 09:53

    Take this answer with a large bag of salt. This will work but you generally don't want to muck around with reflection unless you're very comfortable with Java.


    You can accomplish #2 with reflection, ignoring all sorts of nasty exceptions that you'll have to deal with:

    String st1 = "open";
    String st2 = "Connection";
    URL url = new URL("http://google.co.in");
    Object obj = url.getClass().getMethod(st1 + st2).invoke(url);
    URLConnection connection = (URLConnection) obj;
    

    See:

    • Object#getClass()
    • Class#getMethod(String, Class...)
    • Method#invoke(Object, Object...)

    The potential exceptions you'll have to deal with somehow, from one line of code:

    • NoSuchMethodException
    • SecurityException
    • IllegalAccessException
    • IllegalArgumentException
    • InvocationTargetException

    I'm not really sure why you want to do this, though. There is almost certainly a better way to accomplish the same end result. What is the bigger problem you're trying to solve?

提交回复
热议问题