isInstance() ClassNotFoundException - java

Following is my code which compiles fine but I am getting ClassNotFoundException for case 2 while running, my question is why I am getting error for case 2 :
Case 1
command java Var Var
output false
Case 2
command java Var Object
output ClassNotFoundException : Object
class Var
{
public static void main(String[] args) throws Exception
{
Thread t = new Thread();
System.out.println(Class.forName(args[0]).isInstance(t));
}
}

The fully qualified class name is java.lang.Object.
The compiler automatically imports java.lang.*, that's why you don't have to import classes from this package. However if you call Class.forName you have to use the fully qualified class name.

Related

Under one package : compiler fails to read other class

I have three java files in one package : 'Receiver'.
CMReceiverMutant.java
CMReceiverMutantContext.java
TestDriver.java
Here is my TestDriver.java
package Receiver;
public class TestDriver{
public static void main (String[] args){
TestCase1();
// alternateTestCase1();
}
public static void TestCase1(){
CMReceiverMutant obj = new CMReceiverMutant();
obj.INT1SurvFlag();
obj.Exitw0();
System.out.println("Test case 1 reaches state :"+obj._fsm.getState().getName());
if(obj._fsm.getState().getName().equals("CMReceiverMap.Final"))
System.out.println("Test Case 1 passes!");
else
System.out.println("Test Case 1 fails");
}
}
I compiled TestDriver which depends on CMReceiverMutant.java. Eventhough I put them in the same directory. The compiler seems can't read CMReceiverMutant.java and it makes error :
TestDriver.java:11: error: cannot find symbol
CMReceiverMutant obj = new CMReceiverMutant();
^
symbol: class CMReceiverMutant
location: class TestDriver
I use cmd
javac -classpath Receiver\TestDriver.java
and I've tried
javac -classpath Receiver*.java
The errors are the same. Can you tell me whats the problem is?
Thank you
please check "Source" packages in the "Java Build Path" sometimes if the package isn't registered there the compiler fails to load them.
Hopefully it worked for me.

problems initializing my java method using node-java

I'm not a java jock, but I'm trying to learn how to use node-java. I tried to run one of the examples listed on npm java and gethub node-java and they don't work. I think my method is not initialize in my node.js script correctly. I'm using JDK/JRE 1.8 on a Window 10 laptop. Below is my simple code example. Any help would be appreciated.
var Test = java.import("com.sample.SearchQueryRulesFromTable");
var result = Test.SearchQueryRulesFromTable("C1", "P1");
console.log(result);
Error in node-java
nodeJavaBridge.js:233
return java.newInstanceSync.apply(java, args);
^
TypeError: Could not find method
"com.sample.SearchQueryRulesFromTable(java.lang.String,
java.lang.String)" on class "class com.sample.SearchQueryRulesFromTable".
Possible matches:
public com.sample.SearchQueryRulesFromTable() at Error (native)
at javaClassConstructorProxy….
Here is part of my java code:
...
public class SearchQueryRulesFromTable {
...
public static final void main(String[] args) {...
Results of javap
Compiled from "SearchQueryRulesFromTable.java
public class com.sample.SearchQueryRulesFromTable {
public com.sample.SearchQueryRulesFromTable();
descriptor: ()V
public static final void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
}
#AlphaVictor I have tried to call the main method using node-java constructs that didn't seem to work. I don't know what I'm doing wrong. Below is the main method in SearchQueryRulesFromTable:
ItemSearch item1 = new ItemSearch();
item1.setSearchCustomer(args[0]);
item1.setSearchItem(args[1]);
Using:
java.callStaticMethodSync("com.sample.SearchQueryRulesFromTable",
"ItemSearch(item1)","C1", "P1", function(err, results) {
if(err) {console.error(err);
javaLangSystem.out.printlnSync('test complete! '+ results);return;}
Error:
C:\Users\rdouglas\AppData\Roaming\npm\node_modules\NewProjects\08-
egilerapp1\classes>node test.js
(node) sys is deprecated. Use util instead.
C:\Users\rdouglas\AppData\Roaming\npm\node_modules\NewProjects\08-
egilerapp1\classes\test.js:14
var result =
java.callStaticMethodSync("com.sample.SearchQueryRulesFromTable",
"ItemSearch","C1", "P1")
^
Error:
Could not find method "ItemSearch(java.lang.String, java.lang.String)" on
class "class com.sample.SearchQueryRulesFromTable". No methods with that
name.
at Error (native)
at Object.<anonymous>
(C:\Users\rdouglas\AppData\Roaming\npm\node_modules\NewProjects\08-
egilerapp1\classes\test.js:14:19)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
TypeError: Could not find method
"com.sample.SearchQueryRulesFromTable(java.lang.String,
java.lang.String)" on class "class com.sample.SearchQueryRulesFromTable".
This error tells you that you have tried to call a constructor on class SearchQueryRulesFromTable that accepts two String arguments. There is no such constructor defined on that class.
Your code is attempting to call this non-existent constructor here:
SearchQueryRulesFromTable("C1", "P1");
Depending on what you are trying to do, you may want to call the main method within SearchQueryRulesFromTable instead, and pass it a String[].

Nashorn: How to pre-set Java.type()-vars inside of Java before JavaScript execution?

I am currently executing my JavaScript-scripts with this java code:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("awesome_script.js"));
I need to call Java functions from JavaScript, so I defined this at the top of my awesome_script.js file:
var first = Java.type('io.github.awesomeprogram.FirstClass');
var second = Java.type('io.github.awesomeprogram.SecondClass');
var extra = Java.type('io.github.awesomeprogram.ExtraClass');
I can then call some methods from these classes, e.g.:
second.coolmethod("arg1",2);
My problem is now that I need to use many java classes inside of my scripts. I also have a lot of scripts and I think it is very inefficient to define every single one of this classes in every script.
So I am looking for a solution to create the objects created inside of JavaScript with Java.type() inside of Java and then pass them to the script I want to execute.
How can I do this?
Thanks in advance!
You may want to avoid using the "internal" classes in packages like "jdk.internal.", "jdk.nashorn.internal.". In jdk9, dynalink is an API ("jdk.dynalink" has exported packages). In jdk9, you can call jdk.dyanlink.beans.StaticClass.forClass(Class) [ http://download.java.net/java/jdk9/docs/jdk/api/dynalink/jdk/dynalink/beans/StaticClass.html#forClass-java.lang.Class- ] to construct "type" objects and expose those as global variables to the script engine. For jdk8, you could pre-eval a script that uses Java.type(String) calls before evaluating "user" scripts. You can also call "Java.type" function from Java code.
Solution for jdk9:
import jdk.dynalink.beans.StaticClass;
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.put("AList", StaticClass.forClass(java.util.ArrayList.class));
e.eval("var al = new AList(); al.add('hello'), al.add('world')");
e.eval("print(al)");
}
}
Solution for jdk8:
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// eval a "boot script" before evaluating user script
// Note that this script could come from your app resource URL
e.eval("var AList = Java.type('java.util.ArrayList')");
// now evaluate user script!
e.eval("var al = new AList(); al.add('hello'), al.add('world')");
e.eval("print(al)");
}
}
Alternative solution for jdk8:
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// get Java.type function as object
JSObject javaTypeFunc = (JSObject) e.eval("Java.type");
// you can javaTypeFunc from java code many times
Object alType = javaTypeFunc.call(null, "java.util.ArrayList");
// expose that as global
e.put("AList", alType);
// now evaluate user script!
e.eval("var al = new AList(); al.add('hello'), al.add('world')");
e.eval("print(al)");
}
}
After quite a bit of research I found a way to put global variables in the ScriptEngine before executing: The Java Scripting API (Oracle Docs)
This enabled me to put any object I want into a global variable. However, I still needed a way to get the Object that Java.type() creates inside of Java. So I wrote a test script which returns one of this objects and I found out it is an object of the type jdk.internal.dynalink.beans.StaticClass. This class has an constructor which takes a ordinary Class as an argument. Sadly, this constructor is not usable in my code because it is not visible. To bypass this I used reflection and made this method:
public StaticClass toNashornClass(Class<?> c) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class<?> cl = Class.forName("jdk.internal.dynalink.beans.StaticClass");
Constructor<?> constructor = cl.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
StaticClass o = (StaticClass) constructor.newInstance(c);
return o;
}
If I pass the Class of the object I want as a global variable I just need to call toNashornClass(Example.class); and put the resulting object into a global var with engine.put("example",object);
It works fine. I can use the example var completely like a var created by Java.type().

Class Not Found Exception while using class Class

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

How to call Selenium to another class : NullPointerException

How can we cal an object selenium to the other file which has half code of selenium.
In PHP i can by following code.
login($this); ----> login($sel){ ..... }
Can i do the same in Java as my selenium setup is in one file and the function which uses it is in another file can we pass the selenium to other as I am getting the NullPointerException.
Let me know if you want more details related to this.
Update
Library.java
public class Library extends SeleneseTestCase {
public int Login() throws Exception {
if (selenium.isElementPresent("companyID")) {
selenium.type("companyID", "COMP");
selenium.click("submit_logon");
selenium.waitForPageToLoad("80000");
}
}
}
Login.java
public class Login extends Library {
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://businessbanking.com/");
selenium.start();
}
public void testAllTests() throws Exception {
Library obj1 = new Library();
obj1.Login();
}
}
As per my observation selenium instance started on login file is not addressed to Library. I tried to pass "selenium" as parameter but failed, in Library i tried "super.setUp()" it also failed.
Thanks.
Replace:
public void testAllTests() throws Exception {
Library obj1 = new Library();
obj1.Login();
}
With:
public void testAllTests() throws Exception {
super.Login();
}
Since your Login class already extends Library it already has the Login() method present in it. What you are currently doing is creating a new Library object which does not run the #Before and hence the Selenium field is not initialised (in the new object).
When a subclass extends a base class it will inherit its methods. This is a fundamental Java and OOP concept.

Categories