Plz check following code.... class testError has been instantiated but still Class not found exception is generated... If that is true then why statement written in exception handler does not get printed??
class testError
{
void display()
{
System.out.println("This is testError Class");
}
}
class checkResult
{
public static void main(String[] args)
{
testError te = new testError();
te.display();// I hope the class has been created
Class cls = Class.forName("testError"); // will throw ClassNotFound exception
// Why??... Though the class has been
// instantiated
// if we try to put it in trycatch block it will work...Why??
try{ Class cls = Class.forName("testError");}
catch(ClassNotFoundException e)
{
System.out.println("Error found"); //"Error found" will not be printed
// as the class has been instantiated
}
}
}
I can't comment - as my reputation is too low, but your code runs and debugs fine - though I had to alter it a little bit to make it compile:
public static void main(String[] args) throws ClassNotFoundException {
testError te = new testError();
Class<?> cls = Class.forName("testError");
try {
cls = Class.forName("testError");
// If you got there then everything went fine
te.display();
}
catch (ClassNotFoundException e) {
System.out.println("Error found");
}
}
How do you run your code (from the command line, in an IDE)? What is the console output?
You have got to give more helpful information if you want people to investigate your issue.
Finally, Java convention specifies that classes name should begin with an uppercase character (CheckResult and TestError). Also you should avoid using classes in the default package, as those cannot be imported.
First of all Follow java naming convention
Make your main class public
Create some package(not good to create in default packag) like mypackage and put the classes inside them
and try to invoke the method this way
String name = packageName.className.class.getName();//get the name of the class
className o = (className)Class.forName(name)
.newInstance();
//will give an instance of type Object so cast it
o.display();// call the method
Related
I've included my code below. Following some other examples, I even tried to dynamically load the class in order to force it to run the static block, but that doesn't solve my problem. The class is loaded and class.getName() is printed successfully, but still, when it gets to the last line in the main method it throws an error saying the array is null.
All the other answers address things which don't seem to apply here, like how using the "final" keyword can allow the compiler to skip static blocks. Any help is appreciated!
package helper;
public class StaticTest {
public static boolean [] ALL_TRUE;
private static void setArray(){
ALL_TRUE = new boolean[8];
for(int i=0;i<ALL_TRUE.length;i++){
ALL_TRUE[i] = true;
}
}
static {
setArray();
}
public static void main(String [] args){
ClassLoader cLoader = StaticTest.class.getClassLoader();
try{
Class aClass = cLoader.loadClass("helper.StaticTest");
System.out.println("aClass.getName() = " + aClass.getName());
} catch(ClassNotFoundException e){
e.printStackTrace(System.out);
}
System.out.println(StaticTest.ALL_TRUE[0]);
}
}
In case anyone else lands here, the problem was that I had checked the Netbeans option "Compile on Save" (under Build->Compiling). Somehow, compiling files immediately upon saving was preventing the static block from being run.
Again, thanks to everyone who chimed in to verify that the code itself worked as expected.
I'm trying to test that a class is not found with UnitTest on Android.
What's going on:
1. I'm writing an android library with transitive dependencies which are resolved in the host application
2. The developer may remove some dependencies for example remove all com.example.package
3. I have a Factory that will try to instantiate (using reflection) an Object and catch the ClassNotFoundException. If the developer remove the dependencies, the exception should be thrown.
4. I want to test this case, but all I found is issue with dependencies, not how to test for it.
Example code I want to test
try {
sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class;
} catch (Exception e){
// <<<< I want to test this case
new ClassNotFoundException("Unable to find OkHttpNetworkResponse.Builder.class").printStackTrace();
return null;
}
library used: hamcrast, mockito, JUnit 4.
Do you know how to do it?
So for me the first thing you need to do is to extract the part of the code that can throw a ClassNotFoundException in order to be able to easily mock it, something like:
public Class<? extends NetworkResponseBuilder> getNetworkResponseBuilderClass()
throws ClassNotFoundException {
// Your logic here
}
Then you can test a real factory instance using Mockito.spy to be able to redefine the behavior of the method getNetworkResponseBuilderClass() as next:
public void testFactoryIfNetworkResponseBuilderNotFound() {
Factory factory = spy(new Factory());
when(factory.getNetworkResponseBuilderClass()).thenThrow(
new ClassNotFoundException()
);
// The rest of your test here
}
public void testFactoryIfNetworkResponseBuilderFound() {
Factory factory = spy(new Factory());
when(factory.getNetworkResponseBuilderClass()).thenReturn(
OkHttpNetworkResponse.Builder.class
);
// The rest of your test here
}
More details about Mockito.spy.
Not quite sure if I understood your question correctly, but you can check with JUnit if an exception gets thrown:
#Test(expected=ClassNotFoundException.class)
public void testClassNotFoundException() {
// a case where the exception gets thrown
}
OkHttpNetworkResponse.Builder might be as follows:
package com.example.model;
public class OkHttpNetworkResponse {
public static class Builder {
}
}
I have a Factory that will try to instantiate (using reflection) an Object and catch the ClassNotFoundException. If the developer remove
the dependencies, the exception should be thrown.
Factory Class: which will create any object might be as follows:
package com.example.factory;
public class Factory {
public static Object getInstance(String className)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
Class clazz = Class.forName(className);
return clazz.newInstance();
}
}
The developer may remove some dependencies for example remove all com.example.package
I want to test this case, but all I found is issue with dependencies, not how to test for it.
FactoryTest Class: which will test whether ClassNotFoundException is thrown or not might be as follows: N.B: please Check the comments carefully.
package com.example.factory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
public class FactoryTest {
Factory factory;
#Test(expected=ClassNotFoundException.class)
public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
ClassLoader loader = FactoryTest.class.getClassLoader();
String directory = loader.getResource(".").getPath() + "/com/example/model";
File dir = new File(directory);
//Checking directory already existed or not..
assertTrue("Directory:"+dir.getPath()+" not exist",dir.exists());
//Deleting directory
deleteDirectoryProgramatically(directory);
//Checking directory already deleted or not..
assertFalse("Directory:"+dir.getPath()+" still exist",dir.exists());
//Now getInstance Method will throw ClassNotFoundException because OkHttpNetworkResponse.Builder.class has been deleted programatically.
Factory.getInstance("OkHttpNetworkResponse.Builder.class");
}
private void deleteDirectoryProgramatically(String directory) {
File dir = new File(directory);
System.out.println(dir.getAbsolutePath());
String[] files = dir.list();
for (String f : files) {
File fl = new File(directory,f);
System.out.println(f+ " deleted?"+fl.delete());
}
System.out.println(dir+ " deleted?"+dir.delete());
}
}
It is very simple issue. JUnit4 exception unit testing is given below with an example. Hope it will clarify you.
MyNumber.java
public class MyNumber {
int number;
public MyNumber div(MyNumber rhs) {
if (rhs.number == 0) throw new IllegalArgumentException("Cannot divide by 0!");
this.number /= rhs.number;
return this;
}
}
MyNumberTest.java
public class MyNumberTest {
private MyNumber number1, number2; // Test fixtures
#Test(expected = IllegalArgumentException.class)
public void testDivByZero() {
System.out.println("Run #Test testDivByZero"); // for illustration
number2.setNumber(0);
number1.div(number2);
}
}
JUnit - Exceptions Test
To test if the code throws a desired exception, use annotation #Test(expected = exception.class), as illustrated in the previous example. For your case it will be
/**
* Check for class not found exception
**/
#Test(expected=ClassNotFoundException.class)
public void testClassNotFoundException() {
.....
}
For better understanding, you can go through this tutorial: Java Unit
Testing - JUnit & TestNG. It contains full running code example
step by step with explanation.
inside catch you can check the object with the instanceof operator as :
try {
sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class;
} catch (Exception e){
if(e instanceof ClassNotFoundException){
// here you can do the code you want in case of ClassNotFoundException thrown
}
}
it is your dictionary problem. in your dictionary in test class will not have . change your dictionary.
Use Class.forName("com.example.ClassName")
try {
Class.forName("com.example.OkHttpNetworkResponse.Builder");
} catch (ClassNotFoundException e) {
// This class was not found
}
See Class.forName(String className)
i am planning for the hot deployment of class using the custom class loader.For this task i have written custom class loader. Which looks like
public class CustomClassLoader extends ClassLoader{
public CustomClassLoader(ClassLoader parent) {
super(parent);
}
public Class loadClass(String name) throws ClassNotFoundException {
if(!"classLoader.TestCase".equals(name))
return super.loadClass(name);
try {
String url = null;
String clzName = null;
url = "file:/home/naveen/workspace/JavaConcept/bin/classLoader/TestCase.class";
clzName = "classLoader.TestCase";
}
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while(data != -1){
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
return defineClass(clzName,classData, 0, classData.length);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Now i have a another class called TestCase which has an method called print().
public void print(){
System.out.println("Hello");
System.out.println("Bye");
}
and i am calling it from main method something like this
public static void main(String arg[]) throws InstantiationException, IllegalAccessException{
TestCase t = new TestCase();
t.print();
try {
ClassLoader classLoader = CustomClassLoader.class.getClassLoader();
classLoader = new CustomClassLoader(classLoader);
Class clz = classLoader.loadClass("classLoader.TestCase");
TestCase t2 = new TestCase();
t2.print();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Now here i want to do one thing that inside a main t.print() method is called which print hello and bye on console. Now i have a another version of this Testcase class's print method which only print Hello. So what i did i stated the program in debug mode and let the program going on untill the classLoader.loadClass() line. then i replaced the Testcase.class from directory structure with new version which print only hello.But still it showing the output Hello and Bye.
Can someone help me what's wrong with this program or my understand regarding the class loader is not correct. Please correct me and help to complete my task.
Custom class loaders are difficult to implement because of the many rules you need to keep in mind. In your case, I guess the problem is that your class file is part of your program, which means that if you try to load a class, the default class loader will load it before calling your loadClass() method that will never be called. Try removing your class file from your classpath so that its not part of your program, then your loadClass() should be called.
Second problem is that you are creating your TestCase object using new, that will invoke the default class loader, a better approach would be to call classLoader.loadClass() and then create an instance from the class returned, but if you cast to TestCase that it means that the class is defined in your default classloader which leads to the first problem. An alternative is to create an interface and cast to that interface in order to call your method.
This question already has answers here:
Better understaning - Class.forName("com.mysql.jdbc.Driver").newInstance ();
(4 answers)
Closed 10 years ago.
I am a java beginner and trying to insert a row in db. This is first time in java i am performing insertion operation. For around 2 Hrs i was googling and frustated and cannot solve my error. I called my friend and he gave live support for me in team viewer and added just one line of code to my program.
Class.forName("com.mysql.jdbc.Driver")
Can anyone please explain why we need to include this in my code before connection string. Is it necessary to place my code there each and every time. Please Explain me in Detail.
Here is some very simplified code that illustrates how driver initialization works. There are 3 classes, please put each one in an appropriately-named file.
import java.util.HashMap;
import java.util.Map;
public class DriverMgr {
private static final Map<String, Class<?>> DRIVER_MAP = new HashMap<String, Class<?>>();
public static void registerDriver(final String name, final Class<?> cls) {
DRIVER_MAP.put(name, cls);
}
public static Object getDriver(final String name) {
final Class<?> cls = DRIVER_MAP.get(name);
if (cls == null) {
throw new RuntimeException("Driver for " + name + " not found");
}
try {
return cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Driver instantiation failed", e);
}
}
}
public class MysqlDriver {
static {
// hello, I am a static initializer
DriverMgr.registerDriver("mysql", MysqlDriver.class);
}
#Override
public String toString() {
return "I am the mysql driver";
}
}
public class TestProg {
public static void main(final String... args) {
try {
Class.forName("MysqlDriver"); // try with or without this
} catch (Exception e) {
throw new RuntimeException("Oops, failed to initialize the driver");
}
System.out.println(DriverMgr.getDriver("mysql"));
}
}
When you call Class.forName, the driver class gets loaded and the static initializer gets executed. That in turn registers the driver class with the driver manager, so that the manager is now aware of it. Obviously, this only needs to be done once.
Class.forName("com.mysql.jdbc.Driver")
It must be required to load the driver of database which you are using.
the forNmae() method in this line load the driver of mysql database.
Yes , it's necessary to include every time .
but you can use a method for not repeating the codes .
for example
public void connectToMYSQL(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase","username",""password);
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
and before writing any sql statement , just call the method for example
public void insert(String sql)
{
connectToMYSQL();
//.. then do your stuffs
}
The basic idea is that this action forces the driver class to be registered in JDBC's driver manager.
The method Class.forName("fully qualified class name) is used to initialize the static fields of the class and load the JDBC driver class, MySQL driver in your case, to your application. When it is instantiated, it gets registered with the DriverManager. By the latter you create connections, using Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","login","password");, which you later use to query the database.
I have Java-related question:
I want to know is there a way to create path to class (in program) by using a variable(s).
Im making a program that will download pictures from certain sites and show them to a user. However, different sites have different forms, that's why I have to define a series of functions specific to each. They cannot be put in the same class because functions that preform same job (just for another site) would have to have same names. I'm trying to make adding support for another site later as simple as possible.
Anyway, the question is, could I call a function in program using a variable to determine its location.
For example: code.picturesite.functionINeed();
code is the package containing all of the coding, and picturesite is not a class but rather a variable containing the name of the desired class - that way I can only change value of the variable to call a different function (or the same function in a different class).
I don't really expect that to be possible (this was more for you to understand the nature of the problem), but is there another way to do what I'm trying to achieve here?
Yes, there is a way. It's called reflection.
Given a String containing the class name, you can get an instance like this:
Class<?> c = Class.forName("com.foo.SomeClass");
Object o = c.newInstance(); // assuming there's a default constructor
If there isn't a default constructor, you can get a reference to one via c.getConstructor(param1.getClass(), param2.getClass(), etc)
Given a String containing the method name and an instance, you can invoke that method like this:
Method m = o.getClass().getMethod("someMethod", param1.getClass(), param2.getClass(), etc);
Object result = m.invoke(o, param1, param2, etc);
I'm not immediately seeing anything in your question that couldn't be solved by, instead of having a variable containing a class name, having a variable containing an instance of that class -- to call a function on the class, you would have to know it implements that function, so you could put the function in an interface.
interface SiteThatCanFoo {
void foo();
}
And
class SiteA extends Site implements SiteThatCanFoo {
public void foo() {
System.out.println("Foo");
}
}
Then:
Site currentSite = getCurrentSite(); // or getSiteObjectForName(siteName), or similar
if (SiteThatCanFoo.isAssignableFrom(currentSite.class)) {
((SiteThatCanFoo)currentSite).foo();
}
So you want to do something like this (check ImageDownloader.getImageFrom method)
class SiteADownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteADownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteA
return i;
}
}
class SiteBDownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteBDownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteB
return i;
}
}
// MAIN CLASS
class ImageDownloader {
public static Image getImageFrom(String serverName, URI uri) {
Image i = null;
try {
// load class
Class<?> c = Class.forName(serverName + "Downloader");
// find method to dowload img
Method m = c.getDeclaredMethod("getImage", URI.class);
// invoke method and store result (method should be invoked on
// object, in case of static methods they are invoked on class
// object stored earlier in c reference
i = (Image) m.invoke(c, uri);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
return i;
}
// time for test
public static void main(String[] args) {
try {
Image img = ImageDownloader.getImageFrom("SiteB", new URI(
"adress"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}