0

Let's say I have this code:

public class MyClass {
    public void doSomething(int value) {

    }
}
public class MyNewClass {
    public static void main(String args[]) {
        MyClass myClass = new MyClass();
    }
}

Would it be possible to get a compiler error that doSomething(int) from MyClass has not been called in MyNewClass? I know realistically you would put that method in the constructor but this question is out of curiosity.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • 2
    Would you mind explaining your use case for this? Look at factory methods and private constructors if additional set up is needed after instantiation. – Paul Bellora Aug 13 '13 at 16:04
  • 1
    Using plain Java, no. You can get something like this using aspect programming e.g. [aspectj](http://eclipse.org/aspectj/) – Luiggi Mendoza Aug 13 '13 at 16:04
  • Java doesn't care what methods you don't call. – Dave Newton Aug 13 '13 at 16:05
  • You'd probably have to [use custom annotations](http://stackoverflow.com/questions/10205261/how-to-create-custom-annotation-with-code-behind) to enforce something like this – Brad Mace Aug 13 '13 at 16:07
  • @Paul Bellora Well I was thinking along the lines of some information you would need for a part of a class to work but that you would not necessarely have when you instantiate it. But yeah, after thinking about it for a while, I can't come up with a specific scenario where you would absolutely need this. That's why I put out of curiosity. – user2657455 Aug 13 '13 at 17:31
  • The answers given are quite interesting and diverse. Thanks! – user2657455 Aug 13 '13 at 17:32
  • Ok, I found a situation where this would be very useful. In android, onActivityResult is only available to an activity. If I make a separate class that does not extend/implement onActivityResult, I would have to call (using the example above) doSomething(int value), otherwise the class will not do it's job. – user2657455 Aug 14 '13 at 15:48

1 Answers1

0

The closest you can come to this is using code coverage tools. Providing you have a full set of unit tests, they will allow you to identify, for example, which methods are never called. I can't recommend one library in particular but there are plenty available.

Joe
  • 46,419
  • 33
  • 155
  • 245