Reputation: 3956
I created a custom component which extended from JTextField
. I want to prevent calling getText()
method from my component. Is there a solution for this problem?
Upvotes: 1
Views: 177
Reputation: 918
I am not sure of what are you trying to do, but if what you want is that nothing happens when you call getText, just override it and make it return empty string or nothing. It might help if you explain a bit more of what are you after.
EDIT: just read your comment, then do both. @Override and @Deprecated :)
Upvotes: 1
Reputation: 1980
Calling the getText cannot be prevented, as you cannot reduce visibility on override, so you can choose any other option, like returning a null value or throwing an exception like UnsupportedOperationException, explaining in the javadoc, what is the method doing.
The problem with either solution is if you are using a JTextField variable you might be expecting the getText() method to return something else
JTextField textField = new YourTextField();
textField.getText(); //--> might throw an UnsupportedOperationException instead of NullPointerException (as the javadoc says)
Upvotes: 1
Reputation: 129477
Throw an UnsupportedOperationException
in the method. There is no way to disallow calling getText()
at compile-time, so the runtime exception is the best alternative.
Additionally, from a documentation standpoint, it would be wise to clearly state (in the Javadocs, presumably) that getText()
is not supported by your class. That's really the best warning you can give - it's the responsibility of whoever is using your class to ensure that they fully understand how it works before using it.
Upvotes: 2
Reputation: 41935
You can use UnsupportedOperationException
.
@Override
@Deprecated //will allow caller to see that calling this method should not be called
public void someMethod(){
throw new UnsupportedOperationException("This method is not supported");
}
Upvotes: 2
Reputation: 8928
Override it and throw UnsupportedOperationexception in method body or just leave it empty.
Throwing exception will guarantee you that this method is never used since you'll be getting exceptions otherwise and fix.
Upvotes: 2
Reputation: 62854
Override it, provide a dummy implementation (or just throw UnsupportedOperationException
) and mark it as @Deprecated
.
Upvotes: 4
Reputation: 9741
Override it with a dummy implementation and add documentation mentioning Not to be used!
or throw an exception from inside.
Upvotes: 1