Renaming openconnection() or cutting it up?

2019-03-05 22:08发布

问题:

Is it possible to rename the openconnection()?

Orginal:

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

After:

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

I'm just wondering if it is possible and how I would go about doing it. Is there an alternative? I was thinking of making a class in order to do this, but I wasn't 100% sure if that would be possible.

<------------------ Or ---------------->

Orginal:

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

After:

string st1 = "open";
string st2 = "Connection";
URL url = new URL("http://google.co.in");
URLConnection connection = url.**st1 + st2**();

I get an error when I make it a string, but I'm not really sure how to make it combine the two to define that. If that makes since, I'm kinda rusty at coding with Java.

回答1:

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?



回答2:

For the first part, you can't do that directly. You can't derive from URL since it's final, so you'd have to write a proxy class, and that would be a waste of time and could introduce bugs.

For the second one, you could sort of do that using reflection. It's not trivial to do, that's an advanced topic. So I'd avoid that until you are very familiar with the Java language in general.

If you explained what you were trying to achieve, maybe you'd get better suggestions.



标签: java class url