I am absolute clueless why the following code keeps throwing NullpointerExceptions. I was not able to understand or debug this (its stripped down code from a larger class)...
The code is based on the "Enum Pattern" and I want to keep a List/Map of all "Constants" that are contained in the class (I might be using Reflection for this but using a List/Map is much easier...)
public class Country {
public static final Country SWITZERLAND = new Country("SWITZERLAND");
private static ArrayList<Country> countries = new ArrayList<Country>();
private Country(String constname) {
//constname is currently not used (I will use it for a Key in a Map)
System.out.println(constname);
System.out.println("Ref debug:"+this);
//Ad this to the Countries
Country.countries.add(this);
}
}
Help would be very much appreciated. What am I missing here?
SWITZERLAND, being static, is potentially initialized before countries, which is also static. Therefore, countries is still null in the constructor call of SWITZERLAND.
To force a well-defined order of initialization, use a static block:
public class Country {
public static final Country SWITZERLAND;
private static ArrayList<Country> countries;
static {
countries = new ArrayList<Country>();
SWITZERLAND = new Country("SWITZERLAND");
}
}
To expand on what Konrad said, the static variable initializers are executed in textual order (as specified in JLS section 8.7). If you put the ArrayList first, it will work:
public class Country {
private static ArrayList<Country> countries = new ArrayList<Country>();
public static final Country SWITZERLAND = new Country("SWITZERLAND");
...
Konrad's suggestion of using a static constructor to keep the order clearly specified is a good one though.
Are you using Java "pre 1.5"? If not, use a straight enum...
Because I think this deserves more than the cursory mention Jon gave it:
The "typesafe enum pattern" is obsolete!
Unless you are forced to use an ancient Java version (pre 1.5, which isn't even supported anymore by Sun), you should use Java's real Enums, which save you a lot of work and hassles (because old-style typesafe enums are very hard to get right) and are just all around awesome.
'Country' constructor call to initialize SWITZERLAND static field happens before initialization of countries list. If you change order of static field definition it will work better.
I think code bellow may work .Constructor of class have to define as public method not private.
Country(String constname) {
//constname is currently not used (I will use it for a Key in a Map)
System.out.println(constname);
System.out.println("Ref debug:"+this);
//Ad this to the Countries
Country.countries.add(this);
}
Related
i am a begginer with Java but i want to ask if i can append a method inside a list and how can i make a list? here is my code
public class My_Zoo {
private String Animal_name;
private String Cohabitation;
private String Gender;
private int Weight;
private int Maximum_age;
private String Animal_code;
public void Get_Animal(String A_name, String C, String G , int W , int M_a, String A_c ){
Animal_name = A_name;
Cohabitation = C;
Gender = G;
Weight = W;
Maximum_age = M_a;
Animal_code = A_c;
}
public void Tiger(){
Animal_name = "Tiger";
Cohabitation = "mammal";
Gender = "Female";
Weight = 170;
Maximum_age = 15;
Animal_code = "A01";
}
}
As you are starting with Java I think there are some things that we might say.
Java Conventions
In Java the name of everything has a convention, you can find it here:code conventions
Let me say some that might help you:
Class names: you do not use undescore, you will allways use CamelCase with first letter in capital, for exemple insteade of My_Zoo you should use MyZoo
Variable and parameters name: same as above, but withou first letter in capital, instead of Animal_name you should use animalName
Constructors
I noticed that you tried to make 2 constructors, Get_Animal and Tiger. In java all constructors have the same name of the class. If you do not put any constructors inside a class Java will use the default constructor that looks like this.
public MyZoo(){}
The only difference allowed between constructors is it´s parameters, so you cannot create it with different names, but you can make static methods that create objects for you:
public static MyZoo Tiger(){
MyZoo tiger = new MyZoo();//create the object
//use this to set the fields you you want
return tiger; //return the desired object
}
You can make the methods getAnimal and Tiger to be this way.
More information about static methods: static methods
Lists
In Java we have a class called Collections, on java.util package. All forms of collections extends from it, including the List class.
Those classes has methods to abstracts arrays and matrices processes. More about it: Collections
As it means only to hold a set of values your question doesn´t make sense, it seems that you are asking how to put a method inside a class. To me it appears you are mistaking list with class concept.
Although with java 8 or +, you can use the functional interface an make use of the function as a high order cientizen concept and add methods to a list, that must be a list of methods from the begning, as you are starting in Java and it is a advanced concept I don´t think it is your doubt.
Methods
At least let´s go to your question, but you already made it. Methods in java has 3 basic components: access modifier, return type and a name. You made 2: Get_Animal and Tiger. In Java syntax they are methods, not constructors as I said earlier. If you want put more methods just follow these rules, it´s pretty simple: Java Methods
I hope that things got more clear for you.
And you should learn more about Object Oriented concepts as weel, for example encapisulation, so you can access your fields from outside this class, you noted them with private modifier, so outside your class no one can see them.
Right now what I am doing is this:
public class Values {
List<Line> _lines = new ArrayList<>();
public class Line {
public Line() {
Values.this._lines.add(this):
}
public Values get_parent() {
return Values.this;
}
}
}
This means that when I have a Line I can get the Values class it belongs to, and when I have Values by accessing the _lines instance variable I can get a list of all the lines that belong to the Values object.
This works fine and I have no problem with it, but just so I know , is there a way to get all the instances of Line created under each class of Values without using reflection?
As a side note I'm just saying without reflection because in the old days we always used to avoid reflection because it was too intense on the processor, this may have changed, I just still mistrust reflection and try to avoid it when possible
Thanks in advance for any help you can provide
Edit: I may have explained incorrectly what I wished to do, I'm sorry for that, here's what I was asking
The above code is what I'm using now, what I wish to use is something like this:
public class Values {
public class Line {
}
}
so assuming the above scenario, is there a way to do this without reflection?
Values v = new Values();
Line l1 = v.new Line();
Line l2 = v.new Line();
List<Line> = some magical way to retrieve all lines from v;
I'm sorry for the confusion
Your _lines variable has the default access modifier which meants it's package private docs.
So the answer is depends. If the class accessing the variable is from the same package then no you do not need reflection. If it's not then either reflection or a getter is what you want.
If an object reference is passed to a method, is it possible to make the object "Read Only" to the method?
Not strictly speaking. That is, a reference that can mutate an object can not be turned into a reference that can not mutate an object. Also, there is not way to express that a type is immutable or mutable, other than using conventions.
The only feature that ensure some form of immutability would be final fields - once written they can not be modified.
That said, there are ways to design classes so that unwanted mutation are prevented. Here are some techniques:
Defensive Copying. Pass a copy of the object, so that if it is mutated it doesn't break your internal invariants.
Use access modifiers and/or interface to expose only read-only methods. You can use access modifieres (public/private/protected), possibly combined with interface, so that only certain methods are visible to the other object. If the methods that are exposed are read-only by nature, you are safe.
Make your object immutable by default. Any operation on the object returns actually a copy of the object.
Also, note that the API in the SDK have sometimes methods that return an immutable version of an object, e.g. Collections.unmodifiableList. An attempt to mutate an immutable list will throw an exception. This does not enforce immutability statically (at compile-time with the static type system), but is is a cheap and effective way to enforce it dynamically (at run-time).
There has been many research proposals of Java extension to better control of aliasing, and accessibility. For instance, addition of a readonly keyword. None of them is as far as I know planned for inclusion in future version of Java. You can have a look at these pointers if you're interested:
Why We Should Not Add ''Read-Only'' to Java (yet) -- it lists and compare most of the proposals
The Checker Framework: Custom pluggable types for Java -- a non intrusive way to extend the type system, notably with immutable types.
The Checker Framework is very interesting. In the Checker Framework, look at Generic Universe Types checker, IGJ immutability checker, and Javari immutability checker. The framework works using annotations, so it is not intrusive.
No, not without decorating, compositing, cloning, etc.
There's no general mechanism for that. You'll need to write special-case code to achieve it, like writing an immutable wrapper (see Collections.unmodifiableList).
You could achieve a similar thing in most cases by cloning the Object as the first statement of the method, such as this...
public void readOnlyMethod(Object test){
test = test.clone();
// other code here
}
So if you called readOnlyMethod() and pass in any Object, a clone of the Object will be taken. The clone uses the same name as the parameter of the method, so there's no risk of accidentally changing the original Object.
No. But you could try to clone the object before passing it, so any changes made by the method won't affect the original object.
making it implement a interface which has only read only methods (no setter methods) this gives a copy of an object (road-only copy) and returning the read only instance of interface instead of returning the instance of an object itself
You could define all parameters of the objects as final but that makes the object read only to everyone.
I believe your real question is about avoiding escape references.
As pointed out in some answers to extract an Interface from class and expose only get methods. It will prevent modification by accident but it is again not a foolproof solution to avoid above problem.
Consider below example:
Customer.java:
public class Customer implements CustomerReadOnly {
private String name;
private ArrayList<String> list;
public Customer(String name) {
this.name=name;
this.list = new ArrayList<>();
this.list.add("First");
this.list.add("Second");
}
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public ArrayList<String> getList() {
return list;
}
public void setList(ArrayList<String> list) {
this.list = list;
}
}
CustomerReadOnly.java:
public interface CustomerReadOnly {
String getName();
ArrayList<String> getList();
}
Main.java:
public class Test {
public static void main(String[] args) {
CustomerReadOnly c1 = new Customer("John");
System.out.println("printing list of class before modification");
for(String s : c1.getList()) {
System.out.println(s);
}
ArrayList<String> list = c1.getList();
list.set(0, "Not first");
System.out.println("printing list created here");
for(String s : list) {
System.out.println(s);
}
System.out.println("printing list of class after modification");
for(String s : c1.getList()) {
System.out.println(s);
}
}
}
Ouput:
printing list of class before modification
First
Second
printing list created here
Not first
Second
printing list of class after modification
Not first
Second
So, as you can see extracting interface and exposing only get methods works only if you don't have any mutable member variable.
If you have a collection as a member variable whose reference you don't want to get escape from class, you can use Collections.unmodifiableList() as pointed out in ewernli's answer.
With this no external code can modify the underlying collection and your data is fully read only.
But again when it comes to custom objects for doing the same, I am aware of the Interface method only as well which can prevent modification by accident but not sure about the foolproof way to avoid reference escape.
Depending on where you want the rule enforced. If you are working collaboratively on a project, use final with a comment telling the next person they are not meant to modify this value. Otherwise wouldn't you simply write the method to not touch the object?
public static void main(String[] args) {
cantTouchThis("Cant touch this");
}
/**
*
* #param value - break it down
*/
public static void cantTouchThis(final String value) {
System.out.println("Value: " + value);
value = "Nah nah nah nah"; //Compile time error
}
So specifically to this method, the value will never be written to, and it is enforced at compile time making the solution extremely robust. Outside the scope of this method, the object remains unaltered without having to create any sort of wrapper.
private boolean isExecuteWriteQueue = false;
public boolean isWriting(){
final boolean b = isExecuteWriteQueue;
return b;
}
Expanding on ewernli's answer...
If you own the classes, you can use read-only interfaces so that methods using a read-only reference of the object can only get read-only copies of the children; while the main class returns the writable versions.
example
public interface ReadOnlyA {
public ReadOnlyA getA();
}
public class A implements ReadOnlyA {
#Override
public A getA() {
return this;
}
public static void main(String[] cheese) {
ReadOnlyA test= new A();
ReadOnlyA b1 = test.getA();
A b2 = test.getA(); //compile error
}
}
If you don't own the classes, you could extend the class, overriding the setters to throw an error or no-op, and use separate setters. This would effectively make the base class reference the read-only one, however this can easily lead to confusion and hard to understand bugs, so make sure it is well documented.
I am considering a design in Java where I want a string object but with more 'type-safety' than just being of class String. This because I have a number of 'POJO' objects for Hibernate, representing my database tables. Each of these classes has a large number of public static fields representing the properties of the class, I.e.:
public class PersistantBean {
public static String PROP_FIELD_COLUMN_ONE="columnOne";
public static String PROP_FIELD_COLUMN_TWO="columnTwo";
// [...]
These properties are used when we need to access a property in a generic way, e.g. for code I am currently writing .parseAndSet(PROP_FIELD_PRICE,"£3.00").
I would like to be able to add a stronger type to the PROP_FIELD_... fields so that I could write
public class PersistantBean {
public static PropertyName PROP_FIELD_COLUMN_ONE="columnOne";
public static PropertyName PROP_FIELD_COLUMN_TWO="columnTwo";
// [...]
with minimal changes to other parts of the project,
so that parseAndSet would look like:
public void parseAndSet(PropertyName prop, String priceToParse)
Essentially, I would like PropertyName to be a type that is like String in everyway apart from the compiler would error if I tried to put a String where a PropertyName was expected, is any design pattern like this possible.
(I am shying away from Enums, although now I mention it, Enums may be the way to go.)
For Java 1.5 and above, just use an enum type.
For Java 1.4 and below, use the typesafe enum pattern. E.g.
public class Suit {
private final String name;
public static final Suit CLUBS =new Suit("clubs");
public static final Suit DIAMONDS =new Suit("diamonds");
public static final Suit HEARTS =new Suit("hearts");
public static final Suit SPADES =new Suit("spades");
private Suit(String name){
this.name =name;
}
public String toString(){
return name;
}
}
enum(enumeration) is a better idea, which above mentioned scenario.
eg:
enum PROP_FIELD_COLUMN {
columnOne, columnTwo,etc
}
I'd use an Enum. That way you get compile-time checking.
If your Strings really have a good fairly standard naming convention, like "column" + "One", "Two", etc. as in your example, you could save a lot of work by combining an enum for the prefix with an int for the suffix. So, create a class or utility method that takes an enum for the prefix, e.g. COLUMN, and combines it with an int, say 2, to yield "columnTwo".
An alternative might be be for your code, like parseAndSet, to validate the passed in String against an array or Collection of legal Strings, or maybe a regex, and throw an IllegalArgumentException. You'd get runtime checking and if you have good unit tests this could work.
EDIT ADDED
#sethupathi.t had a nice idea in his answer - In some cases it may be preferable to make the 2nd argument (for which I used an int) also an enum.
As far as I can tell, there are two reasonable ways to do what you want to do.
The first way (and probably best way, if it works for you) is to use an enum, as mentioned in another answer.
The second way, which may be necessary if you do not know all of your PropertyName's at runtime, would be to use a PropertyNameFactory along the lines of:
public class PropertyNameFactory
{
public static PropertyName getPropertyName(String propertyName)
{
// Check validity of the propertyName against what ever rules we
// have defined (maybe valid propertyNames are read from a DB at
// startup, etc).
if (isValid(propertyName))
{
// Ideally get from a cache, but for the sake of the example
// we will create a new one...
return new PropertyName(propertyName);
}
throw new IllegalArgumentException("Invalid property name: " + propertyName);
}
}
This is not ideal in that it does not provide true type safety of your property names, but it does ensure their validity.
I have to second the Enum answers.
However, a more literal answer to your question is that Java provides an interface for String-like objects, java.lang.CharSequence, and many parts of the standard Java libraries have been updated to accept CharSequence where appropriate. This will not however give you the behavior that you want, which is to have your class behave as a subtype of String.
I'm trying to figure out the best way to create a class whose sole purpose is to be a container for global static variables. Here's some pseudocode for a simple example of what I mean...
public class Symbols {
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
/* ...and so on for a bunch of these */
}
I don't need constructors or methods. I just need to be able to access these "symbols" from everywhere simply by calling: Symbols.ALPHA;
I DO need the actual value of the String, so I can't use an enum type. What would be the best way to accomplish this?
Well, it's not clear what else you need beyond the code you've already given - other than maybe making the class final and giving it a private constructor.
However, in order to avoid accidentally using an inappropriate value, I suspect you would be better off making this an enum, like this:
public enum Symbol {
ALPHA("alpha"),
BETA("beta");
private final String value;
private Symbol(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
That way:
You can't accidentally use Symbol.ALPHA where you're really just expecting a string
You can't accidentally use a string where you're really expecting a symbol
You can still easily get the string value associated with a symbol
You can switch on the different symbol values if you need to
You can do that using an interface. No need to construct, values are public, static and final, and can obviously be strings. Such an interface would look similar to your class:
public interface Symbols {
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
/* and so on */
}
You can access the fields directly from everywhere in your code (given it's public) as Symbols.ALPHA etc.
Or, you can use an enum even though you want strings - ALPHA.toString() will return "ALPHA" (and if you want a slightly different string, you can override toString())
Are these configuration parameters or simply "constants" which don't change no matter what? For the former, I'd rather create a configuration class and instantiate it with different values for each environment. Then simply use dependency injection to inject these configurations in different classes. If your requirement is the latter or you are not using DI (Spring/Guice), static classes/interfaces are good to go.