java.lang.ClassNotFoundException, PATH is corrent - java

I'm trying to create a simple program, but of course JAVA thinks otherwise: it's not that simple.
I need to dynamically instantiate a class, meaning that the user gives a class name from keyboard, and then an object of the class type with that name is created.
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.*;
public class NimMain {
public static void main(String[] args) throws IOException {
BufferedReader Olvaso = new BufferedReader(new InputStreamReader(System.in));
String be = Olvaso.readLine();
String[] kapcsolo = be.split(" ");
switch (kapcsolo[0]) {
case "uj": uj(kapcsolo);
case "lep":
case "listaz":
case "ment":
case "tolt":
}}
public static void uj(String[] s) {
try {
int b = 2;
String nev = s[1];
Class NimJatek = Class.forName(nev);
Constructor con = NimJatek.getConstructor(String[].class, int.class);
Object xyz = con.newInstance(s,b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The class which fails to instantiate is NimJatek, which is in the same directory, in the same (unnamed) package.
When I try to run this program, it gives the java.lang.ClassNotFoundException error.

I think you baffle yourself by your not very clear constructs. At the end you use the second value of your input string to be loaded as class. If you provide the correct string there it will be laoded correctly. The input string:
"uj NimJatek"
will lead to a correctly found class NimJatek - provided NimJatek is in your root package AND this root package is on your classpath.

Related

How can I list all methods of all imported classes in a file using Java?

My objective is to look at some lines of codes of an external file and count the number of functions of a class are called then.
For example, if I have the following code:
import java.io.BufferedReader;
import whatever.MyClass;
import java.util.ArrayList;
...
...
public void example(){
InputStreamReader isr = new InputStreamReader (whatever);
MyClass object = new MyClass();
someArrayList.add(whatever2)
someArrayList.add(whatever3)
}
In this case, BufferedReader and MyClass functions were called once, and ArrayList functions were called twice.
My solution for that is get a list of all methods inside the used classes and try to match with some string of my code.
For classes created in my project, I can do the following:
jar -tf jarPath
which returns me the list of classes inside a JAR . And doing:
javap -cp jarPath className
I can get a list of all methods inside a JAR whit a specific class name. However, what can I do to get a external methods names, like add(...) of an "external" class java.util.ArrayList?
I can't access the .jar file of java.util.ArrayList correct? Anyone have another suggestion to reach the objective?
The compiler doesn't put the imports into the object file. It throws them away. Import is just a shorthand to the compiler.(Imports are a compile-time feature ).
first step :
use Qdox https://github.com/paul-hammant/qdox to get all the imports in a class :
String fileFullPath = "Your\\java\\ file \\full\\path";
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(new FileReader( fileFullPath ));
JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();
for ( String imp : imports )
{
System.out.println(imp);
}
second step :
inspire from that code , loop through your imports (String array) and apply the same code and you will get the methods .
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Tes {
public static void main(String[] args) {
Class c;
try {
c = Class.forName("java.util.ArrayList");
Arrays.stream(getAccessibleMethods(c)).
forEach(System.out::println);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
result.add(method);
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
}
Output :
public void java.util.ArrayList.add(int,java.lang.Object)
public boolean java.util.ArrayList.add(java.lang.Object)
public boolean java.util.ArrayList.remove(java.lang.Object)
public java.lang.Object java.util.ArrayList.remove(int)
public java.lang.Object java.util.ArrayList.get(int)
public java.lang.Object java.util.ArrayList.clone()
public int java.util.ArrayList.indexOf(java.lang.Object)
public void java.util.ArrayList.clear()
.
.
.
All the code - one class :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.JavaSource;
public class Tester {
public static void main(String[] args) {
// put your .java file path
// CyclicB is a class within another project in my pc
String fileFullPath =
"C:\\Users\\OUSSEMA\\Desktop\\dev\\OCP_Preparation\\src\\w\\CyclicB.java";
JavaDocBuilder builder = new JavaDocBuilder();
try {
builder.addSource(new FileReader( fileFullPath ));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();
for ( String imp : imports )
{
Class c;
try {
c = Class.forName(imp);
Arrays.stream(getAccessibleMethods(c)).
forEach(System.out::println);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
result.add(method);
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
}
Output all the methods within the classes imported in the file CyclicB.java :
private void java.lang.Throwable.printStackTrace(java.lang.Throwable$PrintStreamOrWriter)
public void java.lang.Throwable.printStackTrace(java.io.PrintStream)
public void java.lang.Throwable.printStackTrace()
public void java.lang.Throwable.printStackTrace(java.io.PrintWriter)
public synchronized java.lang.Throwable java.lang.Throwable.fillInStackTrace()
.
.
.
You may look into OpenJDK project that has a Java compiler. Learn to build the modified versions. Investigate the syntax analysis layer of this compiler and find where the method calls are handled. Put the logging into these locations and now you only need to build your java file with the modified compiler to get the information about the calls.
The build is complex, but you will likely only need a careful editing in a few files. It is not exactly very low hanging fruit but I think it should be possible to discover these files and make changes in them, and still may be a simpler/cleaner approach than to implement the own Java syntax parser (also doable with JavaCC).
If you also need to track calls from the external libraries, build them with the modified compiler as well and you will have the needed records.
GNU Classpath is another open source project where you can do the similar thing, and it may be easier to build. However, unlike OpenJDK, GNU Classpath java system library is not complete.
This approach may not discover some methods called during reflection. But it would discover that reflection framework methods have been called. If it is a security - related project, the simplest would be to agree that reflection is not allowed. It is uncommon to use reflection in a normal Java application that is not a framework.

How to pass a file name as parameter, create and then read the file

I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}

How to resolve a custom option in a protocol buffer FileDescriptor

I'm using protocol buffers 2.5 with Java. I have a proto file that defines a custom option. Another proto file uses that custom option. If I persist the corresponding FileDescriptorProto's and then read them and convert them to FileDescriptors, the reference to the custom option is manifested as unknown field. How do I cause that custom option to be resolved correctly?
Here's the code. I have two .proto files. protobuf-options.proto looks like this:
package options;
import "google/protobuf/descriptor.proto";
option java_package = "com.example.proto";
option java_outer_classname = "Options";
extend google.protobuf.FieldOptions {
optional bool scrub = 50000;
}
The imported google/protobuf/descriptor.proto is exactly the descriptor.proto that ships with Protocol Buffers 2.5.
example.proto looks like this:
package example;
option java_package = "com.example.protos";
option java_outer_classname = "ExampleProtos";
option optimize_for = SPEED;
option java_generic_services = false;
import "protobuf-options.proto";
message M {
optional int32 field1 = 1;
optional string field2 = 2 [(options.scrub) = true];
}
As you can see, field2 references the custom option defined by protobuf-options.proto.
The following code writes a binary-encoded version of all three protos to /tmp:
package com.example;
import com.google.protobuf.ByteString;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.example.protos.ExampleProtos;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
*
*/
public class PersistFDs {
public void persist(final FileDescriptor fileDescriptor) throws Exception {
System.out.println("persisting "+fileDescriptor.getName());
try (final OutputStream outputStream = new FileOutputStream("/tmp/"+fileDescriptor.getName())) {
final FileDescriptorProto fileDescriptorProto = fileDescriptor.toProto();
final ByteString byteString = fileDescriptorProto.toByteString();
byteString.writeTo(outputStream);
}
for (final FileDescriptor dependency : fileDescriptor.getDependencies()) {
persist(dependency);
}
}
public static void main(String[] args) throws Exception {
final PersistFDs self = new PersistFDs();
self.persist(ExampleProtos.getDescriptor());
}
}
Finally, the following code loads those those protos from /tmp, converts them back into FileDescriptors, and then checks for the custom option on field2:
package com.example;
import com.google.protobuf.ByteString;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.UnknownFieldSet.Field;
import java.io.FileInputStream;
import java.io.InputStream;
/**
*
*/
public class LoadFDs {
public FileDescriptorProto loadProto(final String filePath) throws Exception {
try (final InputStream inputStream = new FileInputStream(filePath)) {
final ByteString byteString = ByteString.readFrom(inputStream);
final FileDescriptorProto result = FileDescriptorProto.parseFrom(byteString);
return result;
}
}
public static void main(final String[] args) throws Exception {
final LoadFDs self = new LoadFDs();
final FileDescriptorProto descriptorFDProto = self.loadProto("/tmp/google/protobuf/descriptor.proto");
final FileDescriptorProto optionsFDProto = self.loadProto("/tmp/protobuf-options.proto");
final FileDescriptorProto fakeBoxcarFDProto = self.loadProto("/tmp/example.proto");
final FileDescriptor fD = FileDescriptor.buildFrom(descriptorFDProto, new FileDescriptor[0]);
final FileDescriptor optionsFD = FileDescriptor.buildFrom(optionsFDProto, new FileDescriptor[] { fD });
final FileDescriptor fakeBoxcarFD = FileDescriptor.buildFrom(fakeBoxcarFDProto, new FileDescriptor[] { optionsFD });
final FieldDescriptor optionsFieldDescriptor = optionsFD.findExtensionByName("scrub");
if (optionsFieldDescriptor == null) {
System.out.println("Did not find scrub's FieldDescriptor");
System.exit(1);
}
final FieldDescriptor sFieldDescriptor = fakeBoxcarFD.findMessageTypeByName("M").findFieldByName("field2");
System.out.println("unknown option fields "+sFieldDescriptor.getOptions().getUnknownFields());
final boolean hasScrubOption = sFieldDescriptor.getOptions().hasField(optionsFieldDescriptor);
System.out.println("hasScrubOption: "+hasScrubOption);
}
}
When I run LoadFDs, it fails with this exception:
unknown option fields 50000: 1
Exception in thread "main" java.lang.IllegalArgumentException: FieldDescriptor does not match message type.
at com.google.protobuf.GeneratedMessage$ExtendableMessage.verifyContainingType(GeneratedMessage.java:812)
at com.google.protobuf.GeneratedMessage$ExtendableMessage.hasField(GeneratedMessage.java:761)
at com.example.LoadFDs.main(LoadFDs.java:42)
The options for FieldDescriptor for the s field ought to have a field for that custom option, but instead it has an unknown field. The field number and value on the unknown field are correct. It's just that the custom option is not getting resolved. How do I fix that?
You need to use FileDescriptorProto.parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry, and explicitly create an ExtentionRegistry. Here's one way to create an extension registry:
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
com.example.proto.Options.registerAllExtensions(extensionRegistry);
(where com.example.proto.Options is the compiled custom options class)
This obviously only works if you have access to the custom options compiled file on client side. I don't know if there's a way to serialize the extension and deserialize it on the client side.

"Attributes and objects cannot be resolved" - error

The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()

error: non-static variable this cannot be referenced from a static context

I am having problem with this code:
package javaapplication16;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class JavaApplication16 {
public static void main(String[] args) {
NewJFrame n = new NewJFrame();
n.setVisible(true);
InputStream is;
is = this.getClass().getClassLoader().getResourceAsStream("samp.wav");
try {
AudioStream audioStream;
audioStream = new AudioStream(is);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
It is saying that
error: non-static variable this cannot be referenced from a static context
is = this.getClass().getClassLoader().getResourceAsStream("samp.wav");
If I make the InputStream variable static then its telling me illegal start of expression. I have also removed the this keyword. Still the problem is not solving. How can fix it?
Just avoid the problem, like so:
JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav");
To accomplish this, use a class literal instead:
is = JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav");
you cant use this keyword inside a static method. this keyword can only be used
Within an instance method or a constructor. this is a reference to the current object.
try:
is = YourClassName.class.getClassLoader().getResourceAsStream("samp.wav");

Categories

Resources