Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Annotations Writing Your Own Annotation Putting It All Together

Benjamin Cha
Benjamin Cha
2,761 Points

How to add import statements?

I'm not that sure on how to add the import statements outside the classes I'm using. Does anybody know the answer?

Test.java
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD}) 
public @interface Test { 
   int num() default 1;
   boolean enabled() default true;
}
SocialNetworkTest.java
public class SocialNetworkTest {
  @Test(num = 4, enabled = false)
  public void testTweet() {

  }
  @Test(num = 5, enabled = false)
  public void testInsta() { 

  }
  @Test(num = 6, enabled = false)
  public void testFacebook() { 

  }

  public void testPinterest() { 

  }

  public void testSnapchat() { 

  }
}
TestAnalyzer.java
public class TestAnalyzer {
  /**
   *  Counts the number of methods in the class given by `clazz` that have been annotated
   *  with the @Test annotation.
   */
   public static int getNumAnnotatedMethods(Class<?> clazz) {
        int numAnnotatedMethods = 0;
        Method[] methods = clazz.getDeclaredMethods();

        for (Method method : methods) {
            if (method.isAnnotationPresent(Test.class)) {
                numAnnotatedMethods++;
            }
        }

        return numAnnotatedMethods;
    }

    // Example usage:
    public static void main(String[] args) {
        // Assuming `SocialNetworkTest` is the class to analyze
        int numAnnotated = getNumAnnotatedMethods(SocialNetworkTest.class);
        System.out.println("Number of annotated methods: " + numAnnotated);
    }
}

1 Answer

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey Benjamin Cha , thanks for sharing your question!

It looks like you're missing an import statement for Method, which you're using in TestAnalyzer.java

So, be sure to do so at the top of the file, before declaring the class:

import java.lang.reflect.Method;

public class TestAnalyzer {
    ...//stuff
}