I fell over a class which looks like this:
public final class DatabaseType{
public static final DatabaseType TYPE_LIMITED_TEXT = new DatabaseType();
public static final DatabaseType TYPE_UNLIMITED_TEXT = new DatabaseType();
public static final DatabaseType TYPE_DATE = new DatabaseType();
public static final DatabaseType TYPE_DECIMAL = new DatabaseType();
private DatabaseType(){
}
public String toString(){
return "DatabaseType";
}
}
I need to set the type but I want to understand what's happening here and I have no clue how this class works.
Whatever variable I use it will always return an empty DatabaseType, with no information. So I wonder how you can get use of such a class. Maybe there is a name for this type of class?
Basically, the class lists four enumerable constants, which you can use like this in method signatures
public DatabaseType getTypeOfDB();
In client code, you'll have a type-safe way to compare the constants:
if (getTypeOfDB() == DatabaseType.TYPE_LIMITED_TEXT) {
doSomething();
}
Even though the implementation seems a bit clumsy, it quite closely emulates a Java 5 enum, as Gimby pointed out in the comments. The good ideas in the design are the following:
The constructor is private, meaning only the public static final DatabaseType instances declared within the class can exist
The class is final so you cannot work around the above restriction by adding more constants in a subclass
The constant fields in the class have strong typing, i.e. they are not ints, but instead DatabaseTypes, which helps to eliminate bugs caused by typos or "magic numbers" in client code
The modern way to do the same would be using an enum instead:
public enum DatabaseType {
TYPE_LIMITED_TEXT, TYPE_UNLIMITED_TEXT, TYPE_DATE, TYPE_DECIMAL;
}
If you use call the function toString() you will always get the String : DatabaseType.
As i can understand you want to return the name of the variable you created that are DatabaseType.
Create a variable private String name; and modify the constructor like this:
private DatabaseType(String name){
this.name = name;
}
Also create a function
public String getName(){
return this.name;
}
Finally, when you create a databaseType object create it like this:
public static final DatabaseType TYPE_LIMITED_TEXT = new DatabaseType("TYPE_LIMITED_TEXT");
I am trying to use enum element methods inside a jsp.
This is my enum:
public enum someEnum {
INSTANCE {
public String someMethod() {
return "yay";
}
}
public abstract String someMethod();
}
And in my jsp I want to do:
${somethingContainingMyEnum.getSomeEnum().someMethod()}
However, I get
Class javax.el.BeanELResolver can not access a member of class ... with modifiers "public"
I have found a workaround just doing an indirection:
${somethingContainingMyEnum.doSomething()}
and
public String doSomething {
return getSomeEnum().someMethod();
}
Buy I would like to do it without the indirection. Any hint?
Thats a weird enum, they normally look like this :
public enum SomeEnum {
INSTANCE("yay");
private String myStr;
SomeEnum(String myStr){
this.myStr = myStr;
}
public String getMyStr(){
return this.myStr;
};
}
and you would then reference in JSP
${myBean.EnumInstance.MyStr}
There is no such thing as an anonymous method in Java. Are you thinking of anonymous inner classes ? It seems like over complicating things.
I am an intermediate Java programmer, and very often use methods that are able to take a target as a parameter. Methods such as:
String.substring();
String.indexOf();
So I was wondering, how do I create a method that can take a target String, etc.?
String.substring(); and String.indexOf(); are examples of instance methods of the String class. They are methods that act on objects of that class.
String is a final class in Java, and as such it can not be extended to add your own methods to it. You'll have to create your own class.
Perhaps, for example:
public class MyString {
private String s;
public new(String newValue) {
s = newValue;
}
public someNewMethod() {
//do stuff
}
}
Now, on object of your MyString class, you can do this...
MyString ms = new MyString("Hello World.");
ms.someNewMethod();
How can I set or get a field in a class whose name is dynamic and stored in a string variable?
public class Test {
public String a1;
public String a2;
public Test(String key) {
this.key = 'found'; <--- error
}
}
You have to use reflection:
Use Class.getField() to get a Field reference. If it's not public you'll need to call Class.getDeclaredField() instead
Use AccessibleObject.setAccessible to gain access to the field if it's not public
Use Field.set() to set the value, or one of the similarly-named methods if it's a primitive
Here's an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.
import java.lang.reflect.Field;
class DataObject
{
// I don't like public fields; this is *solely*
// to make it easier to demonstrate
public String foo;
}
public class Test
{
public static void main(String[] args)
// Declaring that a method throws Exception is
// likewise usually a bad idea; consider the
// various failure cases carefully
throws Exception
{
Field field = DataObject.class.getField("foo");
DataObject o = new DataObject();
field.set(o, "new value");
System.out.println(o.foo);
}
}
Class<?> actualClass=actual.getClass();
Field f=actualClass.getDeclaredField("name");
The above code would suffice .
object.class.getField("foo");
Unfortunately the above code didn't work for me , since the class had empty field array.
I have a class called ArionFileExtractor in a .java file of the same name.
public class ArionFileExtractor {
public String ArionFileExtractor (String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
However, when I try to invoke ArionFileExtractor in another .java file, as follows:
String afe = ArionFileExtractor("gibberish.txt", "foo", "/foo");
NetBeans informs me that there are incompatible types and that java.lang.String is required. But I coded ArionFileExtractor to return the standard string type, which is java.lang.string.
I am wondering, can my ArionFileExtractor constructor legally return a String?
I very much appreciate any tips or pointers on what I'm doing wrong here.
Constructors create objects, they don't return data.
Your method, ArionFileExtractor(), is not a constructor. Consutructors do not have return types, and look like this:
public ArionFileExtractor (String fName, String startText, String endText) {
//...
}
Note the lack of a return type.
A constructor can only return an instance of object that it constructed - otherwise you have no reference against which to hang on to the object you just created! If you want to make a "utility" call, consider a static method:
public class ArionFileExtractor {
public static String getFileContents(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
Which can be invoked using
ArionFileExtractor.getFileContents(...)
As much as this is surprising, the code you made has a default no argument constructor. ArionFileExtractor is a method that returns a String. I was quite surprised when I first saw code that did this, as it is certainly an accident (as in your case).
You could call you method (just to show this is the case) with:
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
What it really sounds like you are trying to get at is a static method, not a class at all.
public class ArionFileExtractor() {
public static String extract(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
which you would call with:
String afe = ArionFileExtractor.extract("gibberish.txt", "foo", "/foo");
Constructor is not a regular method. It always returns instance of the class that it belongs to. In your example ArionFileExtractor. There is no way to return any other instance.
Notice that you can't specify return type for constructor explicitly nor use return keyword (illegal in this context).
Java compiler treats ArionFileExtractor as an instance method,
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
Constructor can only return instance of its class. It cannot return String.
For instance if you have class SampleClass, constructor can return only object of class SampleClass.
No it should not be able to legally return a String. I'm not sure why Netbeans didn't simply barf at you when you tried to. Maybe it tried to compile it as some sort of static method. Constructors do not generally have return types in code, because when they are compiled they are assigned to return an instance of the class they are constructing.
The easiest (though not necessarily best) way to adapt your code would be to have an empty constructor and turn the current constructor into a static method like this:
public class ArionFileExtractor {
private ArionFileExtractor() {}
public static String ExtractFile(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
The private constructor makes it so that ArionFileExtractor can only be used statically and cannot be instantiated. Then when you use it you simply do this:
String afe = ArionFileExtractor.ExtractFile("gibberish.txt", "foo", "/foo");
Be warned, using static classes is sometimes considered bad form - depending on the situation. So it might be worth while to try and come up with a different way to do this.
No.
A constructor does not really return anything. Instead it builds the object in question.
It looks like you want a utility method here:
public class Whatever {
public static String doStuff(String s) {
return s;
}
}
Yes.Only String class constructor can return string objects out of it ;).
This basically means that the constructor creates the object of the class you are calling.
You need to FIRST create the object (using the constructor) and THEN do stuff with it.
Java has very few smart shortcuts. I