mamecu
mamecu

Reputation: 19

class not found in java reflection

I'm learning java reflection. I am using the following code. But when I run, it gives the error

unreported exception ClassNotFoundException; must be caught or declared to be thrown Class className=Class.forName("First");

Maybe I'm going wrong somewhere. Please help me out. Here's the code:

import java.lang.reflect.Method;
public class First{   
        public void print(){}
        public void ready(){}
    }

public class test{
    public static void main(String args[])
    {
        Class className=Class.forName("com.Test.First");
        Method[] methods=className.getMethods();
        System.out.println("First method is" + methods[0]);
    }
}

Upvotes: 1

Views: 1052

Answers (2)

Saideep Sambaraju
Saideep Sambaraju

Reputation: 94

This line is the problem

Class className=Class.forName("com.Test.First"); 

in the Class.forName("com.Test.First"), you can replace com.Test.First with any gibberish and the compiler shouldn't care enough to validate it for you. All the compiler knows is that it is possible for there to not be a class com.Test.First and therefore you are responsible for handling a ClassNotFoundException.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

All it's saying is that Class.forName throws this (non-runtime) Exception so you must handle it somehow. Here are two ways you could do it

public class test{
    public static void main(String args[]) throws ClassNotFoundException
    {
        Class className=Class.forName("com.Test.First");
        Method[] methods=className.getMethods();
        System.out.println("First method is" + methods[0]);
    }
}

Or

public class test{
    public static void main(String args[])
    {
        try {
          Class className=Class.forName("com.Test.First");
          Method[] methods=className.getMethods();
          System.out.println("First method is" + methods[0]);
       }
       catch (ClassNotFoundException ex) {
         ex.printStackTrace();
       }
    }
}

Upvotes: 1

Related Questions