Why can java annotation contain a field or even a class? - java

Whats the use of fields or classes inside annotations?
public #interface Test {
public String val = "hello"; // WHY??
public static class MyClass {// WHY??
public static void main(String[] args) {
System.out.println(val);
}
}
String value();
}

Fields: because you can define fields in any interface. They're always implicitly public, static and final: in other words, to define constants in the namespace of the interface.
The answer is essentially the same for classes: it's a public, static (but not final) class. it's just a namespace in which to define the class.
To turn the question around: why shouldn't you be able to do this?
There are all sorts of syntactically valid things you can do that you might think are ill-advised. For example:
String String = "String"; String: break String;
is valid, but useless, and confusing. There are 3 different meanings of String here, 4 if you count the literal. This is far less useful than annotation members, but also allowed.
Sometimes it's effort to stop you doing things: it adds complexity to the language, and the compiler to enforce; and in the effort to prevent the odd piece of madness, you might accidentally remove useful expressivity.

Related

Can Instance variables be declared at the bottom of the Class?

I have a question when I saw "Instance variables can be declared in class level before or after use." in the site java_variable_types
I don't understand what is the class level and the meanning of this sequense.
I think they mean that this is legal:
public class Test {
private int someValue;
public int myMethod() {
return someValue + anotherValue;
}
private int anotherValue;
}
(And it is!)
However, I think it is a mistake for the site to describe this as "[i]nstance variables can be declared in class level before or after use".
The phrase "declared in class level" is bad English grammar.
The phrase "in class level" is ambiguous. It could mean declared in the body of a class. However, it could also mean declared as "class-level" (i.e. static) variables. (That is contradictory, and incorrect, but ...)
The phrase "before or after use" is ambiguous. It could mean before or after in the source code file. It could also mean in before or after in the temporal sense. (That would be incorrect. At runtime, all of an object's instance variables are declared and initialized before the code in a method or constructor body is executed.)
While what they are trying to say (I think) in that sentence is correct, they have expressed themselves poorly, and it is clearly causing confusion for some readers.
Instance variable val is declared in line #2( please note the marking) but referenced even before in line #1. You can remove comment from line #3 and comment line #2. Then also it will work.
It means variable val using in line #1 even before declare in case if line#2 consider using after if you consider line#3.
public class prog{
//private int val; //line# 3
public int getVal()
{
return val;//line# 1
}
private int val; //line# 2
prog()
{
val=0;
}
public static void main( String [] args)
{
prog obj= new prog();
System.out.println("val:"+obj.getVal());
}
}
While your reference does a good job of explaining it, I'll add some details for completeness.
An instance variable...
is declared at the class level
can have any visibility that is necessary (public, protected, private, or no modifier to signify package-private)
will receive an initial value after instantiation (that is, you don't have to instantiate the field with a value...but if you don't instantiate a reference value, you may run into a NullPointerException)
The phrase "before or after use" doesn't make much sense, but let's illustrate a scenario:
public class Foo {
private String word;
public void printTheWord() {
System.out.println(word);
}
}
word hasn't been instantiated, but we can use it since it's received an initial value of null. This means that we won't get the value we want, but it will compile.
Contrast this with a local variable. The below code won't compile because word hasn't been instantiated.
public class Foo {
public void printTheWord() {
String word;
System.out.println(word);
}
}
The phrase "before or after use." would mean that the instance variable, which is applicable to the class as a whole ,unlike local variable which is restricted only inside of that method.
It can be declared or initialized at the start of the class,which is generally the most likely way.
Other , inside of the class, it can be declared , after the call of the method using it.
Please find the below code snippet to understand the phrase:
public class InstanceVariable {
//declared before
int foo=4;
public void testInstanceVariableUse(){
System.out.println("The total value of the instance variable is "+ (foo+boo));
}
//declared after
int boo=5;
}
class TestInstanceVariable{
public static void main(String[] args){
InstanceVariable instanceVar = new InstanceVariable();
instanceVar.testInstanceVariableUse();
}
}
Output:
The total value of the instance variable is 9

Java: Is it more appropriate to store constants in an non-method interface or class?

This question has been bothering me forever. I can wait to hear the responses. I see this too often
public interface Istuff
{
public static final int STATE_B = 4;
public static final int STATE_L = 5;
public static final int STATE_U = 6;
}
and also this one
public class MyStuffConstants
{
public static final String STATUS = "STATUS";
public static final String RUNNING = "RUNNING";
}
I would say Enum. as their sole purpose is to represent fixed set of constants.
Simple Example:
enum Season { WINTER, SPRING, SUMMER, FALL }
You should use enum for that. It's too powerful not to use it.
Don't use interfaces for that. It gets very messy as soon as you have many interfaces (which may come from interfaces extending other interfaces) : you need then to precise in what interfaces to pick the constants which nullifies the benefits of defining the constants in an interface.
The clean solution is to have a non instanciable class for that. Of course, when an enumeration is applicable (that is, the values are different possible values in the same semantic field), you should use an enum. But don't use an enum for this kind of constant :
public final static int DEFAULT_WIDTH = 666;
If you can also associate arbitrary data with your enum constants by adding a constructor:
public enum Season {
WINTER(1, 15), SPRING(2, 92), SUMMER(3, 40), FALL(50, 9);
private final int foo;
private final int bar;
Season(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
public int getFoo() {
return foo;
}
public int getBar() {
return bar;
}
}
For the IStuff example I think enums is kind of awkward if you don't actually need the whole exclusive ordering bit - you'll end up basically creating a class for wrapping an integer.
The MyStuffs example makes sense to make an enum out of, as long as the name of the constant works for you.
It comes down to who will be using the constants - sometimes it makes sense to use constants internally in a class (avoiding magic values). In that case "private static final * *;" works fine.
If you want the constants to be useful as part of an API then sure do constants as in iStuff (btw you can lose the "public static final" bit, which is default when putting them like that in an interface).
Edit: and if you don't have an interface to begin with, and you have constants that clearly belong to a specific, even though the constants need to be public, I don't see the need to create a separate interface just to have somewhere to put the constants. If however the constants will be used in two or more classes/apis and belong in one place more than another, then sure why not put the constants in a separate interface.
I think the concept of constants is too complex to be answered by a general "do this" statement.

Extending String for Typesafety - Java

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.

creating an enum/final class in java

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.

How and where to use Static modifier in Java?

How and where should we use a Static modifier for:
1. Field and
2. Method?
For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
But why is it a good practice?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by #duffymo, not in case of Math class).
UPDATE 1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
There is only one 'copy' of a static field/method.
Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
Static uses less memory since it exists only once per Classloader.
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
a static field exists only once. So if you have a simple class (kinda pseudocode):
class Simple {
static int a;
int b;
}
and now you make objects with:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.
Hope that clears it up a little.
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
Most of the posts above are similar, but this post might offer some other insight. When to use Static Modifiers
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
Try it:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}

Categories

Resources