What does '#' mean in java/android [duplicate] - java

This question already has answers here:
What does the # sign means in java? [duplicate]
(4 answers)
Closed 5 years ago.
just started learning android/java and i noticed many appearances of '#' in the code. #Override i can find using google, but the rest of it is a mystery.
Eg while using ButterKnife library we declare variables like this:
#BindView(R.id.note1) TextView importantNote;
Does '#' have any special functionality, or is it just a regular part of method BindView() name? Since I couldnt find anything specific about '#', I came up with an idea it could be some kind of convention. Am I right? If so, what is the convention?

# is declaring an Annotation. When compiling the code, an Annotation Processor is scanning the code for those annotations and can generate code as you need (for example, the BindView annotation generates the findViewById code needed to bind a view to a variable) or as additional compiler instruction (for example, Override makes sure that the variable actually overrides something or else you get a compiler error).
For more on how to create your own annotations (and how annotation processors work) read here: https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/Processor.html

Check out https://docs.oracle.com/javase/tutorial/java/annotations/
These are "annotations".
For example:
#Override
protected void overridenMethod() {
}
Annotations can have arguments, like this:
#SuppressWarnings("unused")
The example of #BindView is an inline annotation. Inline annotations are very uncommon, other examples of inline annotations are very specific #SuppressLint annotations.
You can make your own annotations, however, if you are making annotations for compiler warnings, error etc., in this case the IDE must detect the annotation. For example, SuppressLint will work only if IDE supports the annotation, otherwise, annotation won't have any effect.

Related

How to understand the internal code of annotations [duplicate]

This question already has answers here:
How do annotations like #Override work internally in Java?
(6 answers)
Closed 4 years ago.
I am working on annotations from last few years without understanding how it works internally. But now I want to understand what is the internal logic for a particular annotation.
If I take an example of #autowire or #controller, I understand where to use this annotations but I am facing difficult in finding the logic behind this annotations.
Could someone help me - how to find the code for a particular annotation.
Initially I felt difficult to understand the functionality behind the annotation feature.
To be specific to the answer for every annotation class there will be processor, when we use the annotation the corresponding processor class will be called and will be executed. This corresponding class has to extend AbstractProcessor.

Call method inside annotation in Java [duplicate]

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.

Necessity of Annotation in Java [duplicate]

This question already has answers here:
How and where are Annotations used in Java?
(14 answers)
Closed 8 years ago.
Could anyone please explain what is the necessity of annotations in java? OR Let me put it more specifically as 'What would have happened if there were annotations in java?'.
I have often seen #Override annotation used extensively. But code can compile even without this annotation then what is it's need? I do understand this makes code less prone to spell mistakes but are annotations optional in general?
To quote the Java Tutorials:
Annotations, a form of metadata, provide data about a program that is
not part of the program itself. Annotations have no direct effect on
the operation of the code they annotate.
That does not mean that they are not very useful. The value of the #Override is demonstrated when you apply the annotation to a method that does not actually override any superclass method. The Java compiler will generate an error that alerts the developer that they are not overriding the method they think they are. This effectively turns a run-time error into a compile-time error.
Annotations are also widely used in a number of Java libraries and external libraries. For example, JAXB utilizes annotations to customize the XML text output from its bindings, and Hiberrnate uses annotations to map Java classes to relational database tables.

Iterate on all class having a specific annotation [duplicate]

This question already has answers here:
Scanning Java annotations at runtime
(13 answers)
Can you find all classes in a package using reflection?
(30 answers)
Closed 9 years ago.
I want to write a simple annotation like "#interface MyClassAnnotation" and "#interface MyMethodAnnotation" that targets Classes and Methods! but the main problem is that on main function i need to list all Class and Method instances on all JVM having that annotations! and I do not want to use any extra libraries, just pure built-in java functions.
Can anyone give me a good snippet for it?
You can determine whether your annotation is present on a particular class or method using the getAnnotation element, which is implemented by both Class and java.lang.reflect.Method.
The real question is, which classes and methods do you want to test this on? "All of them" is a bit hard to define. There doesn't seem to be a way to enumerate all of the classes that have been loaded by the JVM.
It's not feasible to go through all classes, you have to somehow narrow the scope. Either provide a configurable list of packages in which the classes with your particular annotation may be in or use the ServiceLoader concept in Java to declare the set of classes you need to find (this is useful if the code loading the service may be know about or link against all the implementations).

Java Annotations

What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?
What are their typical usages?
Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks.
Oracle has a good explanation of the concept and its meaning in Java on their site.
Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have attributes which are the same thing.
Their use is quite diverse. One typical Java example, #Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.
Anders gives a good summary, and here's an example of a JUnit annotation
#Test(expected=IOException.class)
public void flatfileMissing() throws IOException {
readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat");
}
Here the #Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown.
Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code.
Here is an introduction.
To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor.
They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...).
The first thing a newcomer to annotations will ask about annotations is: "What is an annotation?" It turns out that there is no answer to this question, in the sense that there is no common behavior which is present in all of the various kinds of java annotations. There is, in other words, nothing that binds them together into an abstract conceptual group other than the fact that they all start with an "#" symbol.
For example, there is the #Override annotation, which tells the compiler to check that this member function overrides one in the parent class. There is the #Target annotation, which is used to specify what kinds of objects a user defined annotation (a third type of construct with nothing in common with other kinds of annotation) can be attached to. These have nothing to do with one another except for starting with an # symbol.
Basically, what appears to have happened is that some committee responsible for maintaining the java language definition is gatekeeping the addition of new keywords to the java language, and therefore other developers are doing an end run around that by calling new keywords "annotations". And that's why it is hard to understand, in general what an annotation is: because there is no common feature linking all annotations that could be used to put them in a conceptual group. In other words, annotations as a concept do not exist.
Therefore I would recommend studying the behavior of every different kind of annotation individually, and do not expect understanding one kind of annotation to tell you anything about the others.
Many of the other answers to this question assume the user is asking about user defined annotations specifically, which are one kind of annotation that defines a set of integers or strings or other data, static to the class or method or variable they are attached to, that can be queried at compile time or run time. Sadly, there is no marker that distinguishes this kind of annotation from other kinds like #interface that do different things.
By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools.
When do you use Java's #Override annotation and why?
The link refers to a question on when one should use the override annotation(#override)..
This might help understand the concept of annotation better.Check out.
Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API
for example you need to call transaction method for a bank transfer :
without using annotation :
the code will be
transfer(Account account1, Account account2, long amount)
{
// 1: Call middleware API to perform a security check
// 2: Call middleware API to start a transaction
// 3: Call middleware API to load rows from the database
// 4: Subtract the balance from one account, add to the other
// 5: Call middleware API to store rows in the database
// 6: Call middleware API to end the transaction
}
while using Annotation your code contains no cumbersome API calls to use the middle-
ware services. The code is clean and focused on business logic
transfer(Account account1, Account account2, long amount)
{
// 1: Subtract the balance from one account, add to the other
}

Categories