-3

Is there a way (maybe) using Java reflection to make a method inaccessible after a determined condition? I want to configure a connection with a data base only one time using a method.

  • 5
    Why would you want to? code smell? – Scary Wombat Mar 30 '18 at 00:56
  • 4
    A one, a two, a program crashes on you. – Elliott Frisch Mar 30 '18 at 00:56
  • I´m making a program that configures a connection with a data base, and I want to configure it only one time. – Matheus Grossi Mar 30 '18 at 01:03
  • You've already got a decent answer, but another solution to your problem would be using a connection pool (https://stackoverflow.com/questions/2835090/how-to-establish-a-connection-pool-in-jdbc). That's the mechanism you'll use for getting a DB connection when you run in an app server or servlet container, anyway. – Gus Mar 30 '18 at 01:21

1 Answers1

1

If, as per the comment, the objective is to just use a method only once, then no reflection or complicated mechanism is needed. This can easily be achieved via a boolean variable, e.g.

  public class MyClass {
    private boolean methodUsed = false;
    public void runOnceMethod() {
      if (this.methodUsed) {
        return;
      }
      // ...
      // Method logic
      // ...
      this.methodUsed = true;
    }     
  }
PNS
  • 19,295
  • 32
  • 96
  • 143
  • This can also be made more thread-safe by using an `AtomicBoolean` and doing `if (!methodUsed.compareAndSet(false, true)) return;` – Radiodef Mar 30 '18 at 01:11
  • Sure. There are other things to be added there, depending on the use case, but the answer was just demonstrating the possibility. :-) – PNS Mar 30 '18 at 01:12
  • 1
    @MatheusGrossi using reflection, you can change the value of `methodUsed` to `true` and run the method again. In short, what you're looking is not worth the effort. Just make sure the method is executed once in your application. – Luiggi Mendoza Mar 30 '18 at 01:19
  • @LuiggiMendoza: you beat me to it, but you stated it better. Thanks – Hovercraft Full Of Eels Mar 30 '18 at 01:22
  • Using reflection, one can even modify the value of final variables. The answer makes clear that it is applicable if the question is about using the method once, not about protecting it from attacks. :-) – PNS Mar 30 '18 at 13:44
  • @PNS *Using reflection, one can even modify the value of final variables* this is completely wrong. `final` variables cannot be modified, not even using reflection. – Luiggi Mendoza Mar 31 '18 at 17:52