I'm sure this question has allready been answered somewhere, but I' ve searched for half an hour now and I'm running out of keywords, because I have absolutly no idea how to do this.
I have a constructor for a class like this
public MyClass (String name)
{}
what I want is to define Strings so that only those Strings can be entered.
I assume it has something to do with static final strings, but there is quite a lot to be found to those and I dont know how to narrow down the search. Please tell me how that thing I want to do is called, so that I can search for it.
Edit:
Example to what I want:
I want to somehow define a number of Strings. (Or do somethig else that has the same effect, as I said I dont know how to do it)
String one = "ExampleOne";
String two = "ExampleTwo";
so that when I call the constuctor
MyClass myClass = new MyClass("somethingElse");
the constructor wont take it. Or even better eclipse allready showing my what options I have like it does whit "Color. "
Yes you have right you can not override String class because it is final so simply you can create your own StringWrapper class that wraps string.
public class StringWrapper{
private String content;
public StringWrapper(String c){
content = c;
}
//all your methods and fields there, for example delegated methods
public String toString(){
return content.toString();
}
}
But Enum could be also used in your case then you define your Enum values
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.
#Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
public myClass (Color color)
{}
There are two ways you can acheive this, either use a enum as constructor parameter. The enum itself contains only the allowed values, which is what I would do, keep everythign nice an oop and you can add logic to enums at a later date.
Or alternatively you can just check if the constuctor paramters value is valid, by performing a comparison and throwing an exception if not in allowed values. Have a predfined list and then, myList.contains(myString) - throw exception if false.
What I want is to define String so that only those Strings can be entered
I think that what you are after are Enums.
Enums will allow you to define a range of values which you can then use. In the example I have linked, the developer can restrict the type of input that he/she will receive to the days of the week.
You can check it in constructor's body at runtime, or if you want to compile-time checks, then you can use enum type argument (enum is a predefined set of constants).
From what I understand it seems like you want to limit what the String can be.
You would do this by putting conditional statements inside the constructor to weed out any Strings you don't want to be entered that would either notify the user that it is an invalid string or throw an exception, and the remainder of the constructor would only be executed in an else statement once it has passed all the tests making sure it is a valid String
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I want to change an element name in an ArrayList, without changing its value.
Like :-
ArrayList<Integer> array1 = new ArrayList<>();
int num = 1;
array1.add(num);
Now I want to change num to number, but it's value will be 1.
(Is it possible?)
I want to display all the elements in a ArrayList in a swing combo box, but some of the variables show strange names, such as "Client#45673...". But I want the user to see a descriptive name. That is why I want to rename the variables.
OK, so you are wandering up the proverbial garden path with your "change the name of a variable".
Firstly, it is not a variable. When you put something into a collection, Java doesn't remember that at one point you had the value in a variable.
Secondly, values in general and objects in particular don't have names ... unless you specifically implemented some kind of "name" field as part the class definition.
But I think the clue is in this sentence:
... but some of the variables show strange names, such as "Client#45673..."
That's not a name! That looks like the output of the default implementation1 of toString that your Client class is inheriting from java.lang.Object.
If you want to print / display something something more meaningful, your Client class needs to override the toString() method with its own implementation.
For example:
public class Client {
private String myDescription;
public Client(...) {
...
myDescription = /* something */
}
#Override
public String toString() {
return myDescription;
}
}
Your toString method can return anything you want it to ... so long as it is represented as a string.
Incidentally, if you were to print the array1 object in your question, you would see the actual value 1 rather than a "name" (as you called it). This is because java.lang.Integer overrides the toString() method.
1 - The default toString() result consists of the internal class name and the object's identity hashcode value. The latter is a magic number that the JVM generates. It is not guaranteed unique, but it is guaranteed that it won't change for the lifetime of the object. At any rate, you cannot alter the string that is generated by that method ... except by overriding it.
What you're talking about is the output when printing an object. Those objects need to override toString() and return whatever string is deemed appropriate that describes the class or the contents thereof.
Try this.
class Foo {
//#Override
//public String toString() {
// return "This is a foo";
//}
}
Foo f = new Foo();
System.out.println(f);
Now uncomment the toString() method and print it again.
To print arrays, one way is to use Arrays.toString()
int[] arr = {1,2,3,4};
System.out.println(Arrays.toString(arr));
Is there a way I could pass in a dynamic value into a Custom Annotation?
For example as follows:
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface CustomAnnot {
String[] requestKeys();
}
When annotating, I want to pass in the value of the argument dynamically.
#CustomAnnot(requestKeys = {"id"}) // or maybe "#id"
public Object get(String id) {}
To note the above won't just work. Need some form of parsing for this to work.
How can I go about doing this? Trying to find online references and but unable to find anything to aid in this implementation.
#Cacheable in Spring is able to do this thus clearly this is possible. Tried to have a look over the implementation for #Cacheable and to be honest got lost. It's massive and a struggle to debug. Could I get some advice on this implementation or if anyone familiar point to the part where cacheable implements this? Thanks.
EDIT:
I need a way to get values from arguments in a method.
Example.
// maybe in this method I only want String b and c
String method1(String a, String b, String c){
return null;
}
// maybe here I want String a and c
String method2(int d, String a, String b, String c){
return null;
}
// just 1 argument here so only need String a
String method3(String a){
return null;
}
I am looking for a single way to get the values of what I need in 1 way.
I want to write this functionality once and be done with it, not have to come back again for a different method signature.
Thus I was going for a custom annotation which gives me flexibility to decide what values I want so I can pass in an array .
I am trying to pass a variable number of arguments into a constructor, because not all of the values will always be required, and empty values are okay. Can I make it such that I can pass the variables in, in any order, and have them assign to their corresponding variables in the class correctly?
Few things to note in my case is that the variables in the class are Serialized; the values are either a String, an Integer, a boolean, or a Date; and the values passed into the constructor will always match their corresponding class values (If the value in the class is an Integer, an Integer will always be passed in for that value, not a String.parseInt(), for example)
Class Foo {
#SerializedName("id")
private Integer id;
#SerializeName("name")
private String name;
#SerializedName("isFoo")
private Date isFoo;
public Foo (Object... args){
}
}
In the constructor I want to be able to ask if whatever object name matches a variable in the class, to assign it to that variable. So if one of the Object's passed is an Integer named id, is there a way to match it to id? It should be able to be matched in a few cases:
Foo foo = new Foo(id, name) //In this case, the bool would be null
Foo foo2 = new Foo(name, id, isFoo) //Here the Integer is second, but should still be able to be passed in correctly
I think this can be solved via Reflection but I am not sure how. Any help would be amazing.
I answer your actual question below, but answering the underlying desire of the question, you're probably looking for the Builder pattern:
Foo foo = new Foo.Builder().id(id).name(name).build();
Foo foo = new Foo.Builder().name(name).id(id).isFoo(isFoo).build();
It's one of the original Gang of Four patterns.
(In the above I made Builder a nested class within Foo, as the builder class and the thing it builds tend to be intimately related. But that's not necessary, it's just one way it's done.)
...can I assign values to variables based on the variable name?
No. The variables are not passed to your method. The value contained in the variables is read from them, and that value is passed to your method. By the time it gets to your method, there is no connection whatsoever back to the variable the value came from (if, in fact, it came from a variable).
In your specific example, since each of them has a distinct type, you could check each of the entries in args to see what its type is and work from that, but it would be fairly odd and I wouldn't recommend it.
Emphasizing that I wouldn't recommend it, that would look like:
for (Object arg : args) {
if (arg instanceof Integer) {
this.id = (Integer)arg;
} else if (arg instanceof String) {
this.name = (String)arg;
} else if (arg instanceof Date) {
this.isFoo = (Date)arg;
}
}
But again, I wouldn't recommend it, and if I came across it in a code review I'd want a really, really good justification for it. :-)
I have this problem where there are several parts in my code where I check if these certain conditions are met so that I can understand if what I am checking is of one type or the other. this ends up becoming large if else trees because I am making lots of checks, the same checks in each method, and there are several different types the thing I am checking can be. This I know can be solved using objects!
Specifically, the things I am checking are 4 string values from a file. based on these string values, the 4 strings together can make one of 3 types. Rather than making these same checks every time I need to get the type the 4 strings make up, I am wondering if I can create a general object given these 4 strings and then determine if that object is an instanceof either specific class 1, 2, or 3. Then I would be able to cast that general object to the specific object.
Say I name the general object that the 4 strings create called Sign. I would take those 4 strings and create a new Sign object:
Sign unkownType = new Sign(string1, string2, string3, string4);
I need to check which specific type of sign this sign is.
EDIT:
for more detail, the Signs I am checking are not symbols like "+" or "-", they are signs with text like you would see on the road. there are 4 lines on each sign and they need to be checked to see if each line evaluates to match a specific type of sign.
The first line of SignType1 will be different of the first line of SignType2, and I want to take those 4 lines (Strings) and pass it onto an object and use that object throughout my code to get the values from it rather than making the same checks in each method.
If you want me to show some code, I can, but it won't make much sense.
What you seem to asking for is a factory pattern
public interface ISign {
public void operation1();
public void operation2();
}
and a Factory class to generate classes based on input
public class SignGenerator {
public static ISign getSignObject(String str1,String str2, String str3, String str4) {
if(str1.equals("blah blah"))
return new FirstType();
if(str1.equals("blah blah2") && str2.equals("lorem ipsum"))
return new SecondType();
return new ThirdType();
}
}
public class FirstType implements ISign {
}
public class SecondType implements ISign {
}
public class ThirdType implements ISign {
}
Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses first
From what I gathered from your statement.
Say: create the method that returns a certain object provided the given string is equal to whateva value you specify
//provided the objects to be returned are subtypes of Sign
public Sign getInstance(String first, String second, String third, String fourth)
{
if(first==null || second==null || third==null || fourth===null )
return null;
if(compare1.equals(first))
return new SignType1();
else
if(compare2.equals(second))
return new SignType2();
else
if(compare3.equals(third))
return new SignType3();
else
if(compare4.equals(fourth))
return new SignType4();
}
Above code checks and returns thee appropriet instance corresponding to the string passed
Hope that's what was your concern
This may sound very basic... can someone please explain the use of the toString() method and when to effectively use this?
Have done a search on google but could not find any good resource.
In most languages, toString or the equivalent method just guarantees that an object can be represented textually.
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
Objects often implement custom toString behavior so that the method actually tells you something about the object instance. For example, a Person class might override it to return "Last name, First name" while a Date class will show the date formatted according to some default setting (such as the current user interface culture).
There are several situations in which one would wish to override the toString method of a class (most of which are already mentioned in the existing answers), but one of the most common situations in which I have needed to explicitly call toString on an object is when using StringBuilder to construct a String.
public String createString(final String str) {
final StringBuilder sb = new StringBuilder(str);
sb.append("foo");
sb.append("bar");
return sb.toString();
}
You want to display an object and don't want to check if it is null before.
You want to concat Strings and not thinking about a special attribute, just provide a default one to the programmer.
Thus:
out.println("You are " + user);
will display "You are null" or "You are James" if user is null or toString displays "James" for this (existent) instance.
Assuming .NET or Java:
In general, you should overload ToString() when you want a textual representation of your class (assuming it makes sense for your class).
You can use toString() on an class by overriding it to provide some meaningful text representation of your object.
For example you may override toString() on a Person class to return the first and last name.
To string is should be used when you have a need to change a data type to a string. For built in types like int and such there string representations are what you expect. ie
int i = 5;
string s = i.ToString(); //s now equals "5"
Gives you the character string "5" for most complex types and all user created types you need to overload the tostring method or you will only get the name of the class. To string allows you to use the complex formating build into .net with your own objects. you can provide complex formatters like the datetime class does to give flexibility in using your own types.
toString() can be used to avoid the hexadecimal address, so to overcome this problem you need to override toString() then you will get original text format of data.
When you print reference variable then following task will happen.
if reference variable contains null then null value will be displayed.
if reference variable contains address of an object then toString() Method will be called by the JVM automatically.
By default toString() of Object.class will print:
ClassName#HexadecimalOfHashCode
You can override this method in your class to display some meaningful String.
Usually toString() method is used to print contents of an object.This method is already overridden in many java built-in class like String,StringBuffer,integer etc.
It used when we have to display the field values which we initialize through constructor and what to display without using any getter.
import Test.Date;
public class Employ {
private String firstname;
private String lastname;
private Date DOB;
private Date DOH;
public Employ(String name,String lastname,Date DOB,Date DOH)
{
this.firstname=name;
this.lastname=lastname;
this.DOB=DOB;
this.DOH=DOH;
}
public String toString(){
return String.format("%s %s Birthday %s Hired %s",firstname,lastname,DOB,DOH);
}
public static void main (String args[])
{
Date dob= new Date(12,3,1992);
Date doh= new Date(10,6,2005);
Employ em= new Employ("BOB", "Wrigh", dob,doh);
System.out.println(em);
}
}