class one
{
void call()
{
System.out.println(" A method");
}
}
class two extends one
{
void call()
{
System.out.println(" B method");
}
}
public class Dispatch{
public static void main(String[] args) {
one a=new one();
two b=new two();
one r;
r=a;
r.call();
r=b;
r.call();
}
}
IDE used: VSCode
This was an attempt to implement runtime polymorphism. I used the same example used in "Java -the complete reference -Herbert Schildt", but it shows an error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from two to one".
Your example compiles and runs without errors on my machine (using Eclipse).
Some ideas: Maybe your IDE is set to recompile only on manual request (instead of the typical default continuous building). Or maybe your IDE has some weird compiler warning settings configured.
Related
Simple question here. Here is my Java file:
public class Test {
public static void main(String []args) {
System.out.println("It ran!");
}
void a() {
qweifjew;
}
}
When I press "Run" on VS Code, it says build failed do you want to continue? Makes sense since I have compile-time errors. But when I press continue, it is still able to run and display "It ran!". How come?
For more information on the run command:
C:\Users\jeffe\coding-tutorials\learning-jest> cd c:\Users\jeffe\coding-tutorials\learning-jest && c:\Users\jeffe\.vscode\extensions\vscjava.vscode-java-debug-0.27.1\scripts\launcher.bat "C:\Program Files\Java\jdk-11.0.2\bin\java.exe" -Dfile.encoding=UTF-8 -cp C:\Users\jeffe\AppData\Roaming\Code\User\workspaceStorage\5e0a770d0910238b624ead6f98bca1ec\redhat.java\jdt_ws\learning-jest_f8aabfb2\bin Test
It ran!
This is the decompiled .class file of your code:
public class Test {
public Test() {
}
public static void main(String[] args) {
System.out.println("It ran!ddfseffe");
}
void a() {
throw new Error("Unresolved compilation problems: \n\tSyntax error, insert \"VariableDeclarators\" to complete LocalVariableDeclaration\n\tqweifjew cannot be resolved\n");
}
}
You have Auto Save ON in VS code ?
It's able to run a previous successful build to give you an output.
The project I am working on is an API to support two different platforms. At runtime only one of the two platforms will actually be available on the classpath.
For the most part, I have been pretty easily able to write code like this that works fine
if (isPlatformOne()) {
PlatformOne.doSomething();
}
Even if PlatformOne does not exist at runtime, the check beforehand means the code does not run and no error will be thrown. This technique works for the VAST majority of situations however there is one case that I have run into where an error is thrown.
If PlatformOne also implements a nonexistent interface AND that is used with a parameter that ALSO does not exist, then a NoClassDefFoundError is thrown immediately when the containing class is loaded, regardless of whether the code actually executes or not.
Here's an example:
Interface:
public interface DeleteInterface {
void test(DeleteInterface delete);
}
Class:
public class DeleteClass implements DeleteInterface {
#Override
public void test(DeleteInterface delete) {
}
}
Main:
public class Test {
private final boolean test; //Cannot be constant or compiler will erase unreachable code
public Test() {
test = false;
}
public static void main(String[] args) {
if (new Test().test) {
DeleteClass c = new DeleteClass();
c.test(c);
}
System.out.println("SUCCESS!");
}
}
Deleting DeleteClass and DeleteInterface from the jar produces the following error at runtime:
A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: com/kmecpp/test/DeleteInterface
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: com.kmecpp.test.DeleteInterface
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Why is an error thrown only for this specific case, and what's the best way to work around it without access to any of the target platforms' code?
Java validator might throw NoClassDefFoundError before even fully loading your class because of additional validations, like method return types must exist, additionally you are doing that in your Main class that is scanned by JRE on launch as you can see in stack-trace.
Move code that requires not-existing code to other class and then in place where you want to use it first check if that class exist and then invoke method from that extra class:
class MyExtraClass {
public static void doStuff() {
DeleteClass c = new DeleteClass();
c.test(c);
}
}
public boolean checkForClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
// somewhere in your code
if (checkForClass("package.DeletedClass")) {
MyExtraClass.doStuff();
}
This is just safest option for such cases, also if this is very short code you can just use some local class: (but it does not look good in most cases)
// somewhere in your code
if (checkForClass("package.DeletedClass")) {
new Runnable() {
#Override
public void run() {
DeleteClass c = new DeleteClass();
c.test(c);
}
}.run();
}
I had this issue today actually.
Make sure that you are not loading the same class twice in the systems class loader.
I.E) I had a reference being made to a.b.class in a front-end thread, and I was attempting to reference a library method with the same path and class name, and thus threw the same error for me.
I changed the names in the agent references to be different from the front-end references and the error ceased.
hope this can help
Deleting DeleteClass and DeleteInterface from the jar produces the
following error at runtime:
If the needed class does not exist at runtime, for sure, java.lang.NoClassDefFoundError will be thrown.
Even if PlatformOne does not exist at runtime, the check beforehand
means the code does not run and no error will be thrown.
Please check if your code digested the error thrown, if yes, your app won't crash and can execute as normal. E.g. below code snippet will throw the NoClassDefFoundError but won't crash because that you digest the error.
public bool isPlatformOne() {
try {
...
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
If your use case is just to check if a particular class exists, then you can use Class.forName to check the class's existence. E.g.
// className is the fully qualified class name.
public boolean hasClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
Example for using it in code.
if (hasClass("android.support.v7.app.AppCompatActivity")) {
...
}
Dear StackOverflow Community,
I need your help with the compilation of two Java files per JDB`s Command Line Debugger. Unfortunately, I'm not able to debug two Java files.
I know how to run, compile and set Breakpoints with just one Java-File. Everything is great and works fine.
However, I would like to compile two files.
For example one Java-File DoSomething with a simple Method:
public class DoSomething {
int count = 0;
public int getInt() {
int i = 0;
while( i < 10 ) {
count++;
i++;
}
return count;
}
}
And the Main Class:
public class Main {
public static void main( String[] args ) {
DoSomething ds = new DoSomething();
ds.getInt();
}
}
If I start by the command line the Java compiler I can pass a breakpoint.
For example:
jdb Main DoSomething
Initializing jdb ...
stop in DoSomething.getInt
Deferring breakpoint DoSomething.getInt.
It will be set after the class is loaded.
run Main
run Main
And here is the output:
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
VM Started: Error: Master class TestMain could not be found or loaded
The application exited
What am I wrong or where is my error?
Thank you very much!
I know how to convert a file with the javac command but the problem is that I have a file with a thread.start() so when I declare the tread with Thread foo = new Thread(new FooClass()); foo.start(); it says
error: cannot find symbol
Thread foo = new Thread(new fooClass());
^
symbol: class fooClass
location: class main
1 error
Is there some way to compile them together so it recognizes it or to override the error or something? Because my computer cant use Eclipse it wont let me so. If you could tell me how to get this working that would be great!
Here is the full code:
Main.java:
public class Main{
public static void main(String[] args){
Thread foo = new Thread(new fooClass());
fooClass.start();
}
}
and FooClass.java:
public class FooClass implements Runnable{
public void run(){
int time=0;
boolean isDay=true;
while(true){
time++;
System.out.print("A second has passed");
if(time==60){
if(isDay==true){
isDay=false;
System.out.print("It is now night");
}
if(isDay==false){
isDay=true;
System.out.print("It is now day");
}
}
}
try{
Thread.sleep(1);
}catch(Exception e){}
}
}
}
The error has nothing to do with Thread. It says it can't resolve the symbol fooClass, which must resolve to a class.
You either misspelled (hopefully, in fact) the class name or you don't have it in the classpath/on the list of files you are passing javac.
In case Google is confusing you with too many results, this page should be a very good start in your study of how to use javac.
I tried lot of options to fix this , but could not find a solution. I have created the header file and the dll too. Set the class path asd well. Javac command works fine. When I run this file, I get error: Could not find or load main class com.log.jni.example.HelloWorld. Could you please help me. Here is my file.
public class HelloWorld {
private native void print(String path);
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path="C:\\Capture.pcap";
new HelloWorld().print(path);
}
static {
System.loadLibrary("HelloWorld");
}
}
Could it be that your static initializer is failing.
The following code:
public class Main
{
static
{
if (true)
throw new Error("Error is here");
}
public static void main(String... args)
{
System.out.println("I am running");
}
}
produces the output:
Exception in thread "main" java.lang.Error: Error is here
at Main.<clinit>(Main.java:22)
Could not find the main class: Main. Program will exit.
Are there any stack traces printed out before the 'Could not find main class' error? In this example, the class was found but failed to initialize because of the exception thrown in the static initializer. In your code, a likely suspect is that the System.loadLibrary() call fails with an UnsatisfiedLinkError.
The error "Could not find or load main class ..." occurs when the binary file is not built. Click on project, turn off automatic build. Then click on project and build all. Then turn on automatic build.