EzDevInfo.com

annotations interview questions

Top annotations frequently asked interview questions

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?


Source: (StackOverflow)

Spring: @Component versus @Bean

I understand that @Component annotation was introduced in spring 2.5 in order to get rid of xml bean definition by using classpath scanning.

@Bean was introduced in spring 3.0 and can be used with @Configuration in order to fully get rid of xml file and use java config instead.

Would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation? My understanding is that the final goal is to create beans in both cases.


Source: (StackOverflow)

Advertisements

@Nullable annotation usage

I saw some method in java declared as:

void foo(@Nullable Object obj)
{ ... }

What's the meaning of @Nullable here? Does it mean the input could be null? Without the annotation, the input can still be null, so I guess that's not just it?

Thanks


Source: (StackOverflow)

Why does Eclipse complain about @Override on interface methods?

I have an existing project that uses @Override on methods that override interface methods, rather than superclass methods. I cannot alter this in code, but I would like Eclpse to stop complaining about the annotation, as I can still build with Maven.

How would I go about disabling this error?

Note: Due to project requirements, I need to compile for Java 1.5.


Source: (StackOverflow)

How and where are Annotations used in Java?

What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?


Source: (StackOverflow)

@Column(s) not allowed on a @ManyToOne property

I have a JPA entity with a property set as

@ManyToOne
@Column(name="LicenseeFK")
private Licensee licensee;

But when I deploy on JBoss 6 the application throws an error saying:

org.hibernate.AnnotationException: @Column(s) not allowed on a @ManyToOne property

I use Hibernate 3.5 as the JPA 2.0 implementation.

What should I use to reference the foreign key column?


Source: (StackOverflow)

Do I need elements in persistence.xml?

I have very simple persistance.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

    <persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
        <class>pl.michalmech.eventractor.domain.User</class>
        <class>pl.michalmech.eventractor.domain.Address</class>
        <class>pl.michalmech.eventractor.domain.City</class>
        <class>pl.michalmech.eventractor.domain.Country</class>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>

</persistence>

and it works.

But when I remove <class> elements application doesn't see entities (all classes are annotated with @Entity).

Is there any automatic mechanism to scan for @Entity classes?


Source: (StackOverflow)

How to supply value to an annotation from a Constant java

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time. I have an interface as follows,

public interface FieldValues {
   String[] FIELD1 = new String[]{"value1", "value2"};
}

and another class as,

@SomeAnnotation(locations = {"value1", "value2"})
public class MyClass {
   ....
}

I mark many classes with the annotation and I would like to know if I can avoid specifying the strings in every annotation I would instead prefer to use

@SomeAnnotation(locations = FieldValues.FIELD1)
public class MyClass {
   ....
}

However this gives compilation errors like annotation value should be an array initializer etc. Does someone know how I can use a String constant or String[] constant to supply value to an annotation?


Source: (StackOverflow)

What are good uses for Python3's "Function Annotations"

Function Annotations: PEP-3107

I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me?

How it works:

def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
    ... function body ...

Everything following the colon after an argument is an 'annotation', and the information following the -> is an annotation for the function's return value.

foo.func_annotations would return a dictionary:

{'a': 'x',
 'b': 11,
 'c': list,
 'return': 9}

What's the significance of having this available?


Source: (StackOverflow)

Which types can be used for Java annotation members?

Today I wanted to create my first annotation interface following this documentation and I got the compiler error "Invalid type for annotation member":

public @interface MyAnnotation {
    Object myParameter;
    ^^^^^^
}

Obviously Object cannot be used as type of an annotation member. Unfortunately I could not find any information on which types can be used in general.

This I found out using trial-and-error:

String --> Valid

int --> Valid

Integer --> Invalid (Surprisingly)

String[] --> Valid (Surprisingly)

Object --> Invalid

Perhaps someone can shed some light on which types are actually allowed and why.


Source: (StackOverflow)

Why does JPA have a @Transient annotation?

Java has the transientkeyword. Why does JPA have @Transient instead of simply using the already existing java keyword?


Source: (StackOverflow)

Scanning Java annotations at runtime

What is the best way of searching the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

Do you know a library or a Java facility to do this?

Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system find these classes while loading so they are accessible remotely.


Source: (StackOverflow)

Why is not possible to extend annotations in Java?

I don't understand why there is no inheritance in Java annotations, just as Java classes. I think it would be very useful.

For example: I want to know if a given annotation is a validator. With inheritance, I could reflexively navigate through superclasses to know if this annotation extends a ValidatorAnnotation. Otherwise, how can I achieve this?

So, can anyone give me a reason why this design decision?


Source: (StackOverflow)

Injecting Mockito mocks into a Spring bean

I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields.

I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing.

I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.package.Dao" />
</bean>

The error I currently encounter is as follows:

...
Caused by: org...NoSuchBeanDefinitionException:
    No matching bean of type [com.package.Dao] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {
        @org...Autowired(required=true),
        @org...Qualifier(value=dao)
    }
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)

If I set the constructor-arg value to something invalid no error occurs when starting the application context.


Source: (StackOverflow)

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

I am getting the following error when trying to get a JSON request and process it>

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.myweb.ApplesDO]: can not instantiate from JSON object (need to add/enable type information?)

Here is the JSON I am trying to send:

{
  "applesDO" : [
    {
      "apple" : "Green Apple"
    },
    {
      "apple" : "Red Apple"
    }
  ]
}

In Controller , I have the following method signature

@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
    // Method Code
}

AllApplesDO is a wrapper of ApplesDO :

public class AllApplesDO {

    private List<ApplesDO> applesDO;

    public List<ApplesDO> getApplesDO() {
        return applesDO;
    }

    public void setApplesDO(List<ApplesDO> applesDO) {
        this.applesDO = applesDO;
    }
}

ApplesDO

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String appl) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom){
        //constructor Code
    }
}

I am thinking that JACKSON is unable to convert JSON into JAVA objects for sublclasses. Please help with the configuration parameters for JACKSON to convert JSON into JAVA Objects! I am using Spring Framework

EDIT: Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.


Source: (StackOverflow)