I am new to reflection and to practice, I downloaded a random Java project from a website. I decided to find out which class has the main method so I wrote the following code:
package reflection;
import java.io.IOException;
import java.lang.reflect.*;
import java.nio.file.*;
public class FindMethods {
public static void main(String[] args) throws IOException{
if(args.length==0){
System.out.println("Exiting");
System.exit(1);
}else{
Path p = Paths.get(args[0]);
DirectoryStream<Path> allClassFiles = Files.newDirectoryStream(p, "*.class");
for(Path each : allClassFiles){
// System.out.println(each.getFileName());
try {
findMethods(each.getFileName().toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
public static void findMethods(String file) throws ClassNotFoundException{
System.out.println(file);
Class c = Class.forName(file);
Method[] m = c.getDeclaredMethods();
for(Method each : m){
System.out.println(each.toString());
}
}
}
System.out.println(each.getFileName()); properly returns the .class files in the folder however, it is interspersed with stack trace of ClassNotFoundException
The classes are as follows:
Addwindow$1.class
Addwindow$2.class
Addwindow.class
Authorwindow.class
clsConnection.class
clsSettings$1.class
clsSettings.class
Deletewindow$1.class
Deletewindow$2.class
Deletewindow.class
Editwindow$1.class
Editwindow$2.class
Editwindow.class
Emprptwindow$PrintCommand.class
Emprptwindow.class
Helpwindow.class
LoginFrame$1.class
LoginFrame.class
MainMenu$1.class
MainMenu$2.class
MainMenu.class
Payrptwindow.class
printwindow$1.class
printwindow.class
Settingswindow$1.class
Settingswindow.class
What changes do I need to make to the code to get the methods from each class ?
Stack trace:
java.lang.ClassNotFoundException: Settingswindow
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at reflection.FindMethods.findMethods(FindMethods.java:33)
at reflection.FindMethods.main(FindMethods.java:22)
Random project being talked about:
http://projectseminar.org/java-projects/payroll-accounting-system/98/
.class is part of the filename, but it isn't part of the class name. You need to strip it before passing it to Class.forName.
Another issue is that forName expects packages to be separated using periods, rather than than slashes or whatever directory separator your filesystem uses. If everything is in the default package, this shouldn't be an issue though.
If it's still not working, you should double check the classpath.
Class names that contain a $ are anonymous classes within the outer class (determined by the name to the left of the $). You can safely ignore those in your search for main. Just test for the presence of a $ in the class names in your main loop and skip the processing.
Without knowing more about what app you are looking at, I can't say why your code can't find some of the other classes (like clsConnection).
There is a problem in this approach - you load all project's classes. It is better to analize classes without loading them. There are tools for that. Here's what we can do with http://www.jboss.org/javassist
public static void findMethods(String file) throws Exception {
ClassPool cp = ClassPool.getDefault();
try (InputStream is = new FileInputStream(file)) {
CtClass cc = cp.makeClass(is);
for (CtMethod m : cc.getMethods()) {
System.out.println(m);
}
}
}
Related
While I have seen this happen with the main class and fixed it, I am now getting an error in which my main class cannot find another class I've created to make an object. The classes are within the same Eclipse project file, which is using sinbad to read xml. The classes are
public class RiverRunner {
public static void main(String[] args) {
String code1="abag1";
DataSource ds1= DataSource.connectAs("xml","https://water.weather.gov/ahps2/rss/obs/"+code1+".rss");
ds1.setCacheTimeout(100);
ds1.load();
//ds1.printUsageString();'
System.out.printf("");
//Rivers ob1 = new Rivers();
Rivers ob1 = ds1.fetch("Rivers", "title", "geo:lat", "geo:long");
System.out.println(code1 + ": " + ob1);
}
}
public class Rivers {
private String name;
private float lat;
private float lon;
public Rivers(String name, float lat, float lon) {
this.name=name;
this.lat=lat;
this.lon=lon;
}
//as of yet unwritten methods
}
and the precise error is
Exception in thread "main" core.ops.SignatureUnificationException: could not find a class named: Rivers (ds:no-class)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at core.log.Errors.exception(Errors.java:57)
at core.sig.SigUtils.classFor(SigUtils.java:32)
at core.data.DataSource.fetch(DataSource.java:705)
at RequiredPackage.RiverRunner.main(RiverRunner.java:20)
I've heard it has something to do with .classpath, but I do not know how to open or edit that, nor what it should look like. Other .java files within the project display the same issue. Copy pasting a functional .classpath did not work. Finally, RiverRunner recognizes that Rivers is real to some extent, because if I misspell Rivers when creating ob1, it gives a "cannot be resolved to a type" error, which does not occur if called correctly.
I am using Eclipse IDE 2019-12 and using jre1.8.0_231
I wanted to make a library for an adventure game that was able to read json files to convert them to objects. When I exported the library to a .jar file (not runable) an then imported it into my test project in order to make sure everything worked fine, I made the assets source folder and put in Lantern.json, fillied out what i needed and tried to use my library to convert the json file's values into an Item object and ran the method. However when I ran it I got this error...
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONObject
at com.ferisjumbo.adventure.JSONReader.JSONUtil.getJSONObjectFile(JSONUtil.java:28)
at com.ferisjumbo.adventure.JSONReader.JSONReader.getJSONItem(JSONReader.java:11)
at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: org.json.JSONObject
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more
I have tried researching the error, but to me it sounds like jibberish and doesn't make any sense.
Here are some snippits of whats going on...
//Main (located in src folder in project)
import com.ferisjumbo.adventure.JSONReader.Item;
import com.ferisjumbo.adventure.JSONReader.JSONReader;
public class Main {
public static void main(String[] args) {
Item Lantern = JSONReader.getJSONItem("Lantern.json");
System.out.println(Lantern.toString());
}
}
//JSONReader (located in library)
package com.ferisjumbo.adventure.JSONReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
public class JSONReader {
public static Item getJSONItem(String path) {
JSONObject item = JSONUtil.getJSONObjectFile(path);
.....
//JSONUtil (located in library)
package com.ferisjumbo.adventure.JSONReader;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONObject;
public class JSONUtil {
public static String getJSONString(String path) {
Scanner scanner;
InputStream IStream = FileHandler.inputStreamFromFile(path);
scanner = new Scanner(IStream);
String json = scanner.useDelimiter("\\z").next();
scanner.close();
return json;
}
public static JSONObject getJSONObjectFile(String path) {
return new JSONObject(getJSONString(path));
}
Here is the Project tree if you need it
If you need aditional information I can put up more. Thanks!
For some reason, I've been analyzing my own old jar file(unfortunately source code's been lost).
I know what part I'm going to find but can't remember where it is.
So decide to use byte buddy to get all the run flow of jar file. It's enough to log parameter values and return values of all methods in all classes(except library class, e.g, java.lang.*).
I tried sample codes with a little modification, but straggle with just an exception:
public static void premain(final String agentArgs,
final Instrumentation inst) {
System.out.println(
"+++Hey, look: I'm instrumenting a freshly started JVM!");
new AgentBuilder.Default()
.type(ElementMatchers.any())
.transform(new MetricsTransformer())
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(inst);
}
private static class MetricsTransformer implements AgentBuilder.Transformer {
#Override
public DynamicType.Builder<?> transform(
final DynamicType.Builder<?> builder,
final TypeDescription typeDescription,
final ClassLoader classLoader,
final JavaModule module) {
final AsmVisitorWrapper methodsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceMethods.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isMethod()));
final AsmVisitorWrapper constructorsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceConstructors.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isConstructor()));
return builder.visit(methodsVisitor).visit(constructorsVisitor);
}
private static class EnterAdvice {
#Advice.OnMethodEnter
static long enter() {
return System.nanoTime();
}
}
private static class ExitAdviceMethods {
#Advice.OnMethodExit(onThrowable = Throwable.class)
static void exit(#Advice.Origin final Executable executable,
#Advice.Enter final long startTime,
#Advice.Thrown final Throwable throwable) {
final long duration = System.nanoTime() - startTime;
System.out.println(duration);;
}
}
}
byte buddy's versions are 1.9.5, 1.7.11
jdk version: 1.8.0.191
and the Exception in the cmd:
E:\>cd E:\workshop\_android_studio\BounAgent\out\artifacts\BounAgent_jar
E:\BounAgent_jar>java -javaagent:BounAgent.jar -jar untitled.jar
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/matcher
/ElementMatcher
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Sou
rce)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown So
urce)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.matcher.ElementMatche
r
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
FATAL ERROR in native method: processing of -javaagent failed
Thanks in advance.
According to an article I found:
To launch your agent you must bundle the agent classes and resources in a jar, and in the jar manifest set the Agent-Class property to the name of your agent class containing the premain method. (An agent must always be bundled as a jar file, it cannot be specified in an exploded format.)
It appears that your agent JAR file ("BounAgent.jar") does not contain all of the dependencies in the correct form. Specifically, the bytebuddy classes are not in the JAR file. That is causing the agent classes to fail to load.
I'm writing a program for homework and running into an issue I can't seem to resolve. The problem involves simulating the probabilities of a randomwalk ending on any given node (just background, not really relevant to the problem). I've written my own class that uses a hash map to hold node objects (UndirectedGraph and NodeEntry respectively). I've also written a test harness.
Originally all these were in one file but I decided to move the UndirectedGraph and NodeEntry to a separate package...cause that seems like the right thing to do. I've gotten everything fixed up so that testHarness will compile but at runtime I get the following:
Exception in thread "main" java.lang.NoClassDefFoundError: GraphWalker/NodeEntry
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getMethod0(Class.java:2774)
at java.lang.Class.getMethod(Class.java:1663)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: GraphWalker.NodeEntry
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more
from looking around I find a few answers for this, primarily that the classes aren't on the classpath. Thing is I have all these files in the same folder, and my understanding is the current folder is always on the classpath.
here's abbreviated copies of the code:
testHarness:
import java.util.*;
import GraphWalker.*;
public class testHarness {
public static void main (String args[]) {
new testHarness();
}
public testHarness() {
GraphWalker.UndirectedGraph graph = new GraphWalker.UndirectedGraph(3);
// System.out.println(graph.containsNode(1));
graph.addNode(1);
graph.addNode(2);
graph.addNode(3);
UndirectedGraph:
package GraphWalker;
import java.util.*;
public class UndirectedGraph {
/*
* Based in part on UndirectedGraph.java by Keith Schwarz (htiek#cs.stanford.edu)
*/
public HashMap graphMap;
public UndirectedGraph(int numNodes) {
this.graphMap = new HashMap(numNodes);
}
public void addNode (Integer nodeNum) {
graphMap.put(nodeNum, new NodeEntry(1.0f,0.0f));
}
NodeEntry:
package GraphWalker;
import java.util.*;
public class NodeEntry {
// four inherent values
// credit is the current credit of the node
// nextCredit holds the credit for the next step
// adjList holds a list of adjacent node IDs
// degree holds the number of neighbors
public Float credit;
public Float nextCredit;
public ArrayList adjList;
public Integer degree;
public NodeEntry(Float credit, Float nextCredit) {
this.credit = credit;
this.nextCredit = nextCredit;
this.adjList = new ArrayList();
this.degree = 0;
}
public void addEdge(Integer neighbor) {
this.adjList.add(neighbor);
this.degree += 1;
}
each class has quite a bit more code but I don't think it's relevant to the issue. I'm working on Ubuntu 12.04 and trying to compile and run from both command line and using Geany (simple IDE) same behavior either way.
Any help?
Alrighty,
The issue was that the package files needed to be in a separate folder (named for the package, in my case GraphWalker). I'm not entirely clear on why it compiled fine but at runtime when it went to look for the package it seems to have expected/required them to be in their own folder.
I wouldn't consider that a class path issue, per se, since the files being looked for were in a folder that was on the classpath, just not the folder they needed to be in.
Whatever I do I cannot create new instance of class Serwer. Please help, somehow constructor is invisible. I don't understand why is it so. The constructor is public and everything is coded in one file.
I just get this:
java.rmi.StubNotFoundException: Stub class not found: Serwer_Stub; nested exception is:
java.lang.ClassNotFoundException: Serwer_Stub
at sun.rmi.server.Util.createStub(Unknown Source)
at sun.rmi.server.Util.createProxy(Unknown Source)
at sun.rmi.server.UnicastServerRef.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at com.sun.corba.se.impl.javax.rmi.PortableRemoteObject.exportObject(Unknown Source)
at javax.rmi.PortableRemoteObject.exportObject(Unknown Source)
at javax.rmi.PortableRemoteObject.<init>(Unknown Source)
at Serwer.<init>(Serwer.java:13)
at Serwer.main(Serwer.java:35)
Caused by: java.lang.ClassNotFoundException: Serwer_Stub
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
... 10 more
CLASS
import java.rmi.RemoteException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.rmi.PortableRemoteObject;
public class Serwer extends PortableRemoteObject implements MyInterface {
public Serwer() throws RemoteException {
super();
try{
Serwer ref =
new Serwer();
Context ctx = new InitialContext();
ctx.rebind("myinterfaceimplementacja", ref);
}catch(Exception e){e.printStackTrace();}
}
#Override
public String echo(String napis) throws RemoteException {
return "echo" + napis;
}
#Override
public int dodaj(int wrt1, int wrt2) throws RemoteException {
return wrt1 + wrt2;
}
public static void main(String[] args){
try {
new Serwer();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There are two bugs in your code. The first one is the obvious infinite recursion in the Serwer constructor, where you are calling the constructor again and again. This can be fixed by removing that line from the constructor and replace ref with this on the following line:
public class Serwer extends PortableRemoteObject implements MyInterface {
public Serwer() throws RemoteException {
super();
}
#Override
public String echo(String napis) throws RemoteException {
return "echo" + napis;
}
#Override
public int dodaj(int wrt1, int wrt2) throws RemoteException {
return wrt1 + wrt2;
}
public static void main(String[] args){
try {
Serwer ref = new Serwer();
// Context ctx = new InitialContext();
// ctx.rebind("myinterfaceimplementacja", ref);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
However, this bug is unrelated to the ClassNotFoundException you got. What causes the exception is that you use PortableRemoteObject as the base class of your remote implementation. Normally in Java RMI, the stub class (Serwer_Stub) is generated automatically when you export (instantiate) the remote object. But the PortableRemoteObject is an exception to this case. You can solve this two ways:
As Kumar suggested, replace the javax.rmi.PortableRemoteObject with java.rmi.server.UnicastRemoteObject. This way the stub object gets created automatically, and the above code will run happily, I tested it.
public class Serwer extends UnicastRemoteObject implements MyInterface {
If for some reason you must use PortableRemoteObject, then you should generate the stub class manually by using the RMI compiler (rmic) tool that are shipped with the JDK.
First, you compile the Serwer class:
javac Serwer.java
This will generate the Serwer.class file. Then you call the RMIC tool to generate the stub class:
rmic Serwer
This will generate the Serwer_Stub.class file. Now you can run your server:
java Serwer
I also tested this, it starts without any exceptions.
Note that there is another bug in your code with the usage of the Java Naming, causing another exception (NoInitialContextException), but that is also unrelated with the question, that's why I commented it out in the code above. Since I'm no expert in javax.naming, it's up to someone else to help you with that.
Maybe you intended to use RMI registry instead of using Naming by mistake. RMI registry is the native way to bind and lookup remote objects in Java RMI. In this case you should replace the
Context ctx = new InitialContext();
ctx.rebind("myinterfaceimplementacja", ref);
lines with the appropriate RMI registry code:
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("myinterfaceimplementacja", ref);
This will create the RMI registry for you on the standard port (1099). If you run your program, the registry will be created and your remote object will be exported and registered under the given name.
The other way is to write
Registry reg = LocateRegistry.getRegistry();
This makes your program to find an existing registry that is already running. You must start the RMI registry before running your program, by calling the remiregistry tool, that is also part of the JDK:
rmiregistry
Now you can compile and you start your program:
javac Serwer.java
java Serwer
It will start and register your remote object implementation in the registry, making it available to be looked up by the clients.