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]);
}
}
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();
}
}
}
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.
Related
//PrivateMethod.java
class PrivateMethod
{
private void printMessage()
{
System.out.println("hello rakesh:");
}
}
//AccessPrivate.java
import java.lang.reflect.*;
class AccessPrivate
{
public static void main(String args[]) throws Exception
{
Class c=Class.forName("PrivateMethod");
Object o=c.newInstance();
Method m=c.getDeclaredMethod("printMessage",null);
m.setAccessible(true);
m.invoke(o,null);
}
}
Try this code(I tested it on jdk 1.7 from cmd):
Class<?> c=Class.forName("PrivateMethod");
Object o=c.newInstance();
Method m=c.getDeclaredMethod("printMessage");
m.setAccessible(true);
m.invoke(o);
Okay, so don't ask why, but I'm trying to make a universal public static void main() method. I've already tried to use these two methods;
public class Foo {
public static void main(String[] args){
try {
this.getClass().newInstance().check();
} catch(Exception e) {
e.printStackTrace();
}
}
public void check() {
System.out.println("Check succesful");
}
}
The error I get is that this "Cannot be used in a static context"
Okay, so I know I can't use this in a static context, but what I want to know is how I can replace it, without using Foo.check()
If possible, how should I do this? If not, I'd like to know why.
Looking at How to call getClass() from a static method in Java? and Getting the class name from a static method in Java something like
interface Checkable {
public void check();
}
public class Foo implements Checkable {
public static void main(String[] args){
try {
Class currentClass = new Object() { }.getClass().getEnclosingClass();
Checkable instance = (Checkable) currentClass.newInstance();
instance.check();
} catch(Exception e) {
e.printStackTrace();
}
}
public void check() {
System.out.println("Check succesful");
}
}
might do the trick, but I'm not sure I should recommend doing that...
this is the current instance. You don't have an instance in a static method. Please see I want to know the difference between static method and non-static method
Do this instead:
public class Foo {
public static void main(String[] args) {
new Foo().check();
}
public void check() {
System.out.println("Check succesful");
}
}
As an answer to the comment (I don't seem to be able to make comments yet): No. The only other way is to make check() static as well and call Foo.check(), but you didn't want to do that.
There's no this in a static context; that's exactly what static means. The approach you're trying will not work. You could perhaps supply the name of the class you're interested in on the command line.
As, I know in java instance variable cannot be accessed in static block util you don't have object of that class for which class you want to access instance variable and this in java is a instance variable. so you cannot access this variable in any static block or you required object reference for this.for further clarification check here.
why dont you try this ?
public class Foo
{
public static void main(String[] args){
try
{
Foo obj = new Foo();
// this.getClass().newInstance().check();
obj.check();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void check()
{
System.out.println("Check succesful");
}
}
I have this class:
public class SomeClass {
public void someMethod() {} throws someException
public class someException extends Exception { // Exception class
public someException(String message) {
super(message);
}
}
}
Another class:
public class SomeOtherClass {
public static void main (String[] args) {
SomeClass obj = new SomeClass();
try {
obj.someMethod();
} catch (someException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Eclipse complains that "someException cannot be resolved to a type". I tried to add
import SomeClass.someException
But then it says "The import SomeClass cannot be resolved"
You could of course put someException in a separate file, and not make it nested, is this the only way?
You should be able to use the class by qualifying it with the class name, SomeClass.someException. If you'd rather import it, you have to put your code in a package. You can then do:
import yourpkg.SomeClass.someException;
Also, you got the syntax a bit wrong here:
public void someMethod() {} throws someException
it should be
public void someMethod() throws someException {}
(But perhaps that was a typo in your question.)
You may also want to consider making the nested class static unless you really need to reference the enclosing object:
public static class someException extends Exception {
...
}
I have tracked down an error to line 362 of the java.lang.Class class:
Constructor<T> tmpConstructor = cachedConstructor;
The variable does not seem to get assigned. In the debug expression windows it only says "tmpConstructor cannot be resolved to a variable". The cachedConstructor is not null.
An error is only thrown further down when a the newInstance() function is called:
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
Context:
Using JSON Plugin with the Struts2 framework to create Java objects from the received JSON.
The field it is trying to parse is a subclass of an abstract class.
On further inspection (thanks to user902838) I was missing that it can't instantiate an abstract class. So I need to find out how it can instantiate subclasses, which is a different question.
Can someone please explain to me why the tmpconstructor is empty?
It's hard to tell without any information about the class you're trying to instantiate or the exception/error you observe, but my best guess would be that the class does not have a nullary constructor. This program exhibits such a problem:
package example;
public class NewInstanceTest {
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
The problem can be fixed by adding a nullary constructor:
package example;
public class NewInstanceTest {
/* nullary constructor: */
public NewInstanceTest() {
this("default");
}
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
or by removing all non-nullary constructors so that Java will provide a nullary one automatically:
package example;
public class NewInstanceTest {
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
i was trying to run the following code but i am getting error please clarify my doubt
import java.util.*;
class Except
{ public class AlfaException extends Exception{}
public static void main(String[] args)
{
int b;
Scanner s=new Scanner(System.in);
try
{
b=s.nextInt();
}
catch(InputMismatchException ex)
{
try
{
if(('b'> 67)&&('b'<83)){}
}
catch(AlfaException e){
throw new AlfaException("hello");
}
System.out.println("error found");
}
}
}
Except.java:20: non-static variable this cannot be referenced from a static cont
ext
throw new AlfaException("hello");
^
1 error
Static context is a context that runs on class without actual instance of that class. Your main method is static, that means it can only access static variables. However, your AlfaException is not static. Meaning that it will be bound to an instance of Except class - which you do not have.
Therefore you have 2 choises:
Make AlfaException also static: public static class AlfaException extends Exception{}. That will make it reside in static scope so it will be possible to access it from static functions.
Move all the main(...) method logic into non-static context. Create a function called doWork() that is not static, move all the code from main to doWork, and then call it like this:
.
public static void main(String[] args) {
Except instance = new Except();
instance.doWork();
}
Your AlfaException is a non-static inner class of Except, so it can only be instantiated from inside an instance of Except. The main method is static, so doesn't have an enclosing instance.
Change the declaration of AlfaException to:
public static class AlfaException extends Exception{}
and it should work.
There are couple of mistakes:
AlfaException is never thrown in your try-block
AlfaException is a non-static inner class of Except (see other answers)
If you rethrow AlfaException in catch-block, the main needs a throws like this:
public static void main(String[] args) throws AlfaException { ...
import java.util.*;
class Except
{ public static class AlfaException extends Exception{
public AlfaException(String string) {
super();
}
}
public static void main(String[] args) throws AlfaException
{
int b;
Scanner s=new Scanner(System.in);
try
{
System.out.println("Enter the value for b");
b=s.nextInt();
System.out.println("b value is "+b);
}
catch(InputMismatchException ex)
{
if(('b'> 67)&&('b'<83)){}
System.out.println("error found");
}
}
}
output:
Enter the value for b
80b
error found