-
Reflection
I'm making some mods for a game, and I and using java reflection's Field.setAccessible to get fields from classes that I need but weren't originally intended to be accessed. This approach feels a little hacky. :/ I could just modify the access modifier in the code, but this reduces compatibility with other mods, which is a HUGE deal. Is my way fine, or is there another, better way.
-
Re: Reflection
You'll have to provide more details. It's difficult to tell based on the info you've given.
I can imagine two alternatives which may or may not work:
1. See if you can't make something work with inheritance and polymorphism
2. See if you can't replicate the results using other means which don't require modifying accessibility.
As a general rule I avoid reflection like the plague, but sometimes it is necessary.
-
Re: Reflection
Well, as I see it...
1. I can of course override access modifiers with inheritance, however I have no way to put my new class into the system, without severely limiting compatibility.
2. I have to access an object that I have no prior control over, and I have no other way to get it. I may be overlooking something, but I don't think I am.
Is that enough to call reflection necessary, or have I still not given enough info? There's no way I know how to get at the object without reflection. It's a very simple set up. A class with a private variable. It's the first time that variable is brought up in the inheritance chain, and there are no sub classes of the class in question.
-
Re: Reflection
The biggest question is is the data private? If it is you may want to strongly consider alternative solutions. Private is used for a reason because they want to limit external access to the variable.
If it is protected or you can gain access to the variable by extending a class (even if it's just a dummy class to gain access to the variable) I would recommend that route.
There's a good question about the use of setAccessible over at Stack Overflow. Ultimately you'll have to decide if this is something you're willing to do. Personally I avoid reflection whenever possible, sometimes even reducing functionality to do this. However, it is a useful tool, hence its inclusion into Java.
-
Re: Reflection
Thanks. As I see it, the data is private, which is probably because it's part of a gui, and shouldn't be edited (which is exactly what I want to do XD). I really hate the idea of reflection, especially because it pretty much let's you do whatever you want. But I am struggling to find another way. Dummy classes are out of the question, as it can't be inherited. So what are my options, cut and dry? Just reflection?
-
Re: Reflection
Pretty much, unless you go native (in this case a worse option than reflection). But be careful doing it and test your results very carefully.
-
Re: Reflection
Cool, Thanks! I will continue using reflection then. Thanks for the new outlook.