Class not found exception in Java Reflection - java

Hi I am using the following code from this site: http://java.sun.com/developer/technicalArticles/ALT/Reflection/
But when I am running it it showing exception java.lang.ClassNotFoundException: A
May be I am going somewhere wrong Please help.
Here is the code:
package com.Test;
class A {}
public class instance1 {
public static void main(String args[])
{
try {
Class cls = Class.forName("A");
System.out.println("gfsdga");
boolean b1
= cls.isInstance(new Integer(37));
System.out.println(b1);
boolean b2 = cls.isInstance(new A());
System.out.println(b2);
}
catch (Throwable e) {
System.err.println(e);
}
}
}

The class is actually called com.Test.A because you've declared it within the com.Test package - Class.forName() takes the package-qualified class name. (Note that com.Test is a pretty odd package name, too.)

You need Class.forName("com.Test.A") instead.

Related

Check what java class type is this

I want to check String is interface or not using Reflection method .isInterface. Here is what I tried but it gives Class not found exception.
public class CheckingClassType {
public static void main(String args[]) {
try {
Class c = Class.forName("String");
System.out.println(c.isInterface());
} catch (Exception e) {
System.out.println(e);
}
}
}
Use Class c = Class.forName("java.lang.String");
You need to give the full package name of the class. The reflection needs to know that to instantiate the class name as multiple classes with same name can exist in different packages.

Cannot Access Java Class Exception - Access Specifier Limitation

# EvenDriver.java
package com.EventDrivenScenario.SystemElements;
import com.EventDrivenScenario.Exceptions.TableFullException;
import java.util.Random;
public class Table {
static final int TABLE_SIZE = 6;
static int tableCurrentSize;
Table(){
}
public static void main(String args[]){
Random eventTrigger = new Random();
while(true){
try {
if(eventTrigger.nextLong()%2 == 0){
new HumanBeing();
}
if (tableCurrentSize == TABLE_SIZE) {
throw new TableFullException();
}
} catch(TableFullException e) {
System.out.println(e.getMessage());
break;
}
}
}
}
class HumanBeing{
HumanBeing(){
new Chairs();
}
}
class Chairs{
Chairs(){
Table.tableCurrentSize++;
}
}
# TableFullException
package com.EventDrivenScenario.Exceptions;
public class TableFullException extends Exception{
TableFullException(){
}
public String getMessage() {
return ("Table Full - No More Visitors");
}
}
In the above code when i try to compile #EventDriver.java, I am getting compile time error indicating that TableFullException is not public and cannot be accessed outside package in spite of declaring it as public.
but if I change the package statement in both files to ##package com.EventDriver;## It works fine. I just want to understand why the above code throwing compile time error in spite of provide public access specifier for TableFullException.
Your TableFullException constructor is not public, so you can't create an instance of that exception from a class that doesn't belong to the same package. Make the constructor public, and your problem will be solved.
This is because you have a package private constructor for the class.
You have defined a constructor as package private by not giving any access modifier to the constructor Example :
public class PackagePrivateClassConstructor{
PackagePrivateClassConstructor(){}
}
You can use this constructor in the same package but outside the package it won't allow you to use it.
This is true for all you class Table,Chairs & HumanBeing.
You need to change it to
public class MyClass{
public MyCLass(){}
}

I want dynamic way to get the package name from any class in java

I have code like below sample. in that I am telling the class_name to get package name. instead of this method, i need another logic to get the package name withoud telling the class_name directly.
package smk.jsf.bean;
public class test {
public static void main(String[] args) {
System.out.println(test.class.getPackage().getName());
//Is there any option like "this.class.getPackage().getName();" bz. i don't want use class_name direclty
}
}
Output : smk.jsf.bean
Thanks to everyone.
Finally I got solution below
package smk.jsf.bean;
public class test {
public static void main(String[] args) {
String className = new Object(){}.getClass().getPackage().getName();
System.out.println(className);
}
Not sure it will suit you but try sun.reflect.Reflection.getCallerClass(). This class is present in JDK.
It will return a Class instance of method caller. Then just getPackage(). It is really dangerous stuff but it lets you not to use the class name directly.
Example usage - create a method String getPackageName() which will get caller class and return package name and call it from main.
Or you can throw any throwable, catch it and parse that throwable's stack trace to get the target package name (really sick way).
I have two approaches.
You can add a field public static final PACKAGE_INFO = "%package%"; to each file. Then traverse your source directory, read the line with the package package someName and replace the %package%
Use a dynamic approach at runtime. I wrote a little example program.
public class PackageExample {
public static void main(String[] args) throws ClassNotFoundException {
Example e = new Example();
System.out.println(e.getPackage());
}
}
interface MetaInformation {
public String getPackage() throws ClassNotFoundException;
}
class InformationGatherer implements MetaInformation {
public String getPackage() throws ClassNotFoundException {
StackTraceElement[] ste = new Exception().getStackTrace();
if (ste.length < 2)
throw new IllegalStateException("StackTrace to small to determine package!");
String clazz = ste[1].getClassName();
Class<?> c = Class.forName(clazz);
String package_ = "";
Package p = c.getPackage();
if (p != null)
package_ = c.getPackage().getName();
return package_;
}
}
class Example implements MetaInformation {
private InformationGatherer ig = new InformationGatherer();
public String getPackage() throws ClassNotFoundException {
return ig.getPackage();
}
}
Not sure if this helps but you can use reflection
http://docs.oracle.com/javase/tutorial/reflect/
Similar question :
See Can you find all classes in a package using reflection?
If it's a static method.No.
You cannot use this in a static context,since main is static method.
If it is not a static method,
String name = this.getClass().getPackage().getName();

Java - How to create a Class<Map<Object,List<Object>>> object

I'm sorry if this is a noob question. I have a method which takes a Class object with the generic type as a parameter. I am able to do the following:
Class cs = Map.class;
but when I pass this I get an "NoSuchMethodException" since the method is declared:
public void doSomething(Class<Map<Object, List<Object>>> theclass){
...
}
I have tried to cast it like this:
Class cs = (Class<Map<Object, List<Object>>>)(Class<?>)Map.class;
but I still get the same exception.
Is there a way to do this?
I cannot post the full code here but I have reproduced the error:
The application is actually using reflection. I can not post the original code here but I have reproduced the exception:
import java.lang.reflect.Method;
import java.util.*;
public class Main {
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("Second");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String m = "doSomething";
Method method = null;
Class cs = Map.class;
try{
method = c.getMethod(m, cs);
} catch (NoSuchMethodException e){
e.printStackTrace();
}
}
}
class Second{
public static void doSomething(Class<Map<Object, List<Object>>> theclass){
System.out.println("HERE I AM!");
}
}
The exception:
java.lang.NoSuchMethodException: Second.doSomething(java.util.Map)
at java.lang.Class.throwNoSuchMethodException(Class.java:283)
at java.lang.Class.getMethod(Class.java:825)
at Main.main(Main.java:16)
If you're doing such casting, I think you're fighting against the type system that's designed to help you. For starters,
Class cs = Map.class;
is a raw type (see here for more info). Have you tried instantiating a class of your required Map type, and passing the class of that to your function ?
e.g.
(new HashMap<Object, List<Object>>()).getClass();
Note: as ruakh as noted in the comments above, you'd have to pass an instance of the Map interface, and as such that method declaration above would prohibit this. Basically there's a fundamental API design issue here!
Got it! I have changed the following line:
method = c.getMethod(m, cs);
to:
method = c.getMethod(m, cs.getClass());
Now it works!

Java Reflection, Class Objects

My objective is to read in to the command line the name of a Class I wish to observe info on. When I know the class name before runtime, I have no issue. What I can't seem to manage is how to create a class object based on a string input.
public class Tester {
static void methodInfo2(Object obj) throws ClassNotFoundException {
//some stuff
System.out.print("Test!");
}
public static void main (String args[]) throws ClassNotFoundException{
String className = args[0];
System.out.println("Class: "+className);
//myclass2 mc = new myclass2();
//Class c = mc.getClass();
Class argClass = Class.forName(className);
try {
methodInfo2(argClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The 2 commented out lines in the main method show what I have done in the past when I know the class name before I compile. The following uncommented line shows what I thought should work, but I receive a ClassNotFoundException. The class certainly exists so I'm not sure what problem I'm having.
Two suggestions:
Make sure you're giving it the fully-qualified name (e.g. "java.lang.Thread" and not just "Thread").
Make sure the compiled class file is actually on the classpath.
Class.forName is the right way to load a class by name at runtime.
Either your argument is wrong or your class isn't in the classpath.

Categories

Resources