-1

I am trying to add custom function that operates on string variable like below in java (in my android project actually)

String name="tester";
name.isAlreadyEntered();

public static boolean isAlreadyEntered(String name){
    return (checkInMyDb(name));
}

I am going to use this for some more functions. I know its a bit stupid question. I know this does exists in javascript & in .Net. As I am new to java I m not aware of its possibility. Forgive if I am asking wrongly. But if possible please help me on how to get this syntax

Sunil Kanzar
  • 1,244
  • 1
  • 9
  • 21
jafarbtech
  • 6,842
  • 1
  • 36
  • 55
  • 4
    Java does not support the ability to add new methods to standard classes. – khelwood Apr 10 '17 at 15:32
  • The ``String`` class is final, so you cannot even subclass it. – f1sh Apr 10 '17 at 15:38
  • 4
    Doesn't make much sense. if you have a class for your database, you could add it there and use something like `myDatabase.containsPerson(name)`. much more expressive since `isAlreadyEntered()` doesn't give you any context about where you expect it to be entered. – Flikk Apr 10 '17 at 15:43
  • Why you wish to add method to existing class that too which is declared as final. If this is what you really intend to do (adding method to String.java) then you seriously need to rethink and redesign. As I can see you simply can have a method in some of your class where you can check if the `name` is present in the database or not, why and what is the need of modifying `String.java` – nits.kk Apr 10 '17 at 16:07

1 Answers1

1

If you really intend to add a new method to java.lang.String.java then you are probably on a wrong path which will only cause pain and agony in future :d. Better stop, rethink redesign and refactor.

Anyways firstly NO you can not add a new method to String class. It is final and hence you can not and neither you should even intend to sub class it. If you intend to do so then its a poor design, which you must refactor.

If you just wish to check if some String is present in the database, you can simply declare the method which can accept a parameter of type String , check its presence in the database and return true if found else return false.

If above solution does not work for you then you can try takimg help of Composition. If you want a Object with such method (which can tell if the object is present in db) then You can create a class , may decide to name it as per your contextual needs , I am naming it as StringContainer. This class can have a instance variable of type String. Now instead of using String object you can use the object of this newly created custom class composing the object of String You can include a method to check if entry cossponding to an object of this class had been made in database or not.

nits.kk
  • 5,204
  • 4
  • 33
  • 55