This question already has answers here:
Can I add new methods to the String class in Java?
(16 answers)
Closed 5 years ago.
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
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.
Related
This question already has answers here:
Does EL automatically convert/cast the type? How does ${a.name} actually work?
(2 answers)
Closed 2 years ago.
I have these pictures from Head First book:
I want you to pay attention to code that replaces ${person.dog.name}. Only thing I want to know is how does it know that attribute "person" is object of type Person? Of course, getAttribute() returns Object, so it must be casted to Person, but how does it know that it is made from Person class?
I guess this code uses findAttribute() previously, to find scope where attribute with value "person" is stored. Later it tries to get it using getAttribute(). So after it finds it, it gets it - but it still doesn't know what it is getting in reality. So how/where did it "figure out" that it is of type Person?
It doesn't. The properties are resolved using reflection, by looking for a method getDog() on whatever object person resolves to, and then repeating that process.
the EL engine sees person and looks it up in the glorified HashMap (which is what request.setAttribute is filling - that glorified hashmap).
It finds an object there, because you set it. It gets this object and invoked .getClass() on it, which returns Person.class. It then runs a capitalizer function on dog to produce getDog. It then scans for all fields using .getFields() as well as all methods using .getMethods(), looking for either a field named dog or a no-args instance method named getDog. It finds the method, and invokes it.
Repeat this principle for how it ends up dealing with the .name part.
Now EL has an object (the result of invoking getName on whatever object wsas returned by reflectively invoking getDog on whatever person was), and toStrings that into place.
I don't think it's HTML escaping it, so this is a book that is 'helpfully' informing you how to use obsolete technology (JSP) to create security holes. Great.
You got a newer book? You might wanna get something that is less than 10 years old :)
This question already has answers here:
Why must I override toString method instead of just creating another method?
(13 answers)
Closed 4 years ago.
What is the benefit in using toString method in java if it has always need to be overridden?
Example:
String var = "3";
byte [] var_inBytes = var.getBytes();
String var2 = var_inBytes.toString();
this will give me the name of the object followed by the hash code
okay then when we can use toSting method without overriding?
Every Class is inherited from Object Class in Java, Therefore the Object class methods are available to all Java classes.
According to the Java doc :
In general, the toString method returns a string that "textually
represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
You may want to override the default toString() method in your current class to represent a different format string depend on your requirement but since the Object class has this method, All of the other classes have a default toString() method.
You can read more here :
https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#toString()
Good Luck!
toString() method is one of the programmer best friend. I use it on each business object or each entity at least, to list their variable members content.
At the time an unexpected problem occurs and that your are in big trouble, and especially if you are in emergency, it makes a great change if you can read : "Big trouble on item {Id : 125, name : Smith, Address : 15 King Square}", instead of "Big trouble on an item".
Not only you have the id you can use for your internal research, but you can also tell a end-user about who is really impacted : Mr Smith. May be your end-user will have a clue : "Oh yes, we were doing special operation on him, because..."
In plenty of logs, on TRACE or DEBUG level only of course, I dump many business object or entities content that way. If a really big problem happens, even in production, and that it is reproducible, I may (in the dire case) restart the application in TRACE mode and learn what really happens.
toString() is a life savior, I say.
I have a method:
public Question createQuestion(String text, Project project, User createdUser, Date createdDate)
this method is being used to create a question by the controller. Now there is no tag here in the parameters. I want to implement a functionality to add tags to a question.
To add tag I need to pass it a tagSet which can be empty as well when the user does not add tag to a question while creating the question. So, should I pass one more parameter to it and then put an if condition before adding that to the question object or should I write a separate method?
public Question createQuestionWithTags(String text, Project project, User createdUser, Date createdDate,Set<Tag> questionTagSet)
which will call the createQuestion and then will set the questionTagSet in the object returned by the above createQuestion() method. If I write another method then check for the empty tag will be done in the controller and if not then that check condition will be in the utility.
Which approach is better?
Also, how about overloading the method in the same context?
This is an ideal candidate for the Builder Pattern. Declare a builder within Question, setting the parameters using the Fluent Interface Pattern, calling build() at the end to instantiate the appropriately-constructed, concrete Question instance. It would look something like:
Question.builder().withText(text).withProject(project).build();
Occurrences that require a set of tags to be specified would supply suffix the above code with a call to withTags(tags) prior to invoking build().
Well to be honest, taking into consideration of how complicated overloading is in general (JLS wise), I have a hard time saying yes to it. And by hard I mean look at functional interfaces and overloading (or even search this site for related questions to see how people are pulling their hair sometimes - me included). But this is not related to lambdas only, overloading is by some people seen as too complicated and rarely needed, read this for one example.
What you have done with renaming those methods is the cleanest possible ways of achieving the task you have (unless you think of a builder pattern may be).
There can be a lot of good answers to this question and, depending of your specific use case, keep in mind design patterns (and that sometimes antipatterns are justified), best practices, etc, that will make your code better.
That said, Question should have the method for adding new tags since it is the class which has the tags attribute (isn't it?). The way you implement it is up to you. It could be something like:
public class Question {
// ...
public void addTags(Set<Tag> questionTagSet) {
this.tags.addAll(questionTagSet);
//...
}
}
This way wherever you have an object of type Question you can add tags like this:
//...
Set<Tag> tags = new HashSet<>();
Question q = new Question();
q.addTags(tags);
//...
From this point, I think there is no "best" option, but "best option for your use case". So one option would be an overloading (see Method overload below for a detailed explanation) and the other one a new method (with a different signature of course).
Method overload: One method which receives all arguments and other which receives all arguments but questionTagSet, in that one you only call the one which receives all arguments by providing a default value: null. Now, in the method which receives the questionTagSet argument you will call the Question#addTags method if the questionTagSet argument is not null. This will allow you to use the same method signature but with different arguments from the controllers. Thus you don't have to do the checking in every controller (which could be a lot), since you moved the check to only one place: the createQuestionWithTags method.
Something like this:
method with all arguments but questionTagSet
public Question createQuestionWithTags(String text, Project project, User createdUser, Date createdDate) {
return createQuestionWithTags(text, project, createdUser, createdDate, null);
}
method with all arguments
public Question createQuestionWithTags(String text, Project project, User createdUser, Date createdDate,Set<Tag> questionTagSet) {
Question q = new Question();
//... some more additional logic here
if (questionTagSet != null) { //<- logic for adding tags moved here
q.addTags(questionTagSet);
}
return q;
}
This implementation can differ if you wan to do some checks with the questionTagSet argument.
Pros of this:
You can call the method createQuestionWithTags from different controllers in different way without worrying about the questionTagSet param:
utility.createQuestionWithTags("", new Project(), new User(), new Date(), new HashSet<Tag>())
utility.createQuestionWithTags("", new Project(), new User(), new Date(), null)
utility.createQuestionWithTags("", new Project(), new User(), new Date())
Cons
Overloading can be tricky and confusing sometimes
When doing unit test you need to be sure which method are you testing, since the signature is almost the same.
This question already has answers here:
Which types can be used for Java annotation members?
(4 answers)
Closed 4 years ago.
Can I able to call a method which returns string inside an annotation.
If so please guide me how to achieve this?
I tried like this but this doesn't work for me.
#Description(value = Resource.getWord("key"))
An annotation only takes compile time constants (as they might be used during compile time), therefore you cannot make any calculation within the definition, as they are unknown during the compile time.
Allowed constant types are (taken from java-annotation-members):
Primitive
String
Class
Enum
Another Annotation
An array of any of the above
Possible solution for your situation:
As I understand you would like to localize the #Description content.
As this is only meant to be exposed to other developers anyway, you are safe to simply use English, in my opinion. Localization is for the end user, not the developer.
I can imagine an aspect being wired up to process methods annotated like this, where the "key" is in the annotation, and the aspect processing then uses the key at run time... but I'm not sure this is what you're looking for.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What's the best way to refactor a method that has too many (6+) parameters?
If a constructor has a long parameter list, should we consider it bad style and refactor it? If yes, how?
Consider using a Builder. Instead of having a constructor where some of the parameters can be null:
Foo foo = new Foo(name, id, description, path, bar);
And instead of telescoping constructors - i.e. making one constructor for each combination of parameters, you can have:
Foo foo = new FooBuilder().setName(name).setPath(path).build();
It may be an appropriate set of parameters, but a lot of the time my answer would be yes. Break the parameters into a logical subgroupings if they exist i.e. rather than creating a Car from many different parts, group some parts into an Engine object, some into a Chasis etc.
Alternatively, if some of those parameters are optional, make use of the builder pattern so that you only include them when necessary.
Ultimately, though, do whatever makes most sense for you and your domain.
Yes, you should. See What's the best way to refactor a method that has too many (6+) parameters?