Is it possible to change the name of a class retrieved using:Foo.class.getName() (or getSimpleName() or getCanonicalName()).
I know that those methods are part of java.lang.Class<T> the question itself is if there is a way to tell java.lang.Class<T> what is the name that I want it to display for my class.
I know that it "opens the door to tricky things" since that name is used by the reflection libraries to do "stuff" and bla bla bla. nevertheless I was wondering wether is posible to call Foo.class.getSimpleName() and get something like MyFoo.
All of this of course without string manipulation which is the last alternative I have.
Find the src.zip in your JDK. Extract java/lang/Class.java into some directory and modify getSimpleName() method. For example like this:
public String getSimpleName() {
return "MyName"; // return MyName for any class
}
Compile it normally with javac (you will get many warnings, ignore them). Remove all additional classes created like Class$1.class, leaving only java/lang/Class.class file. Put it into jar:
$ jar -c java >myclass.jar
Now prepend the bootstrap path with your new jar. For example, let's consider this test class:
public class Test {
public static void main(String[] args) {
System.out.println(Test.class.getSimpleName());
}
}
$ java Test
Test
$ java -Xbootclasspath/p:myclass.jar Test
MyName
I don't even want to explain how dangerous it is. Also according to the Oracle binary code license (supplemental term F) you cannot deploy your application this way.
You may try Powermock which according to their home page allows mocking final classes although it needs to use it's own class loader.
Other mocking frameworks that do not do byte code manipulation with custom class loaders such as Mockito and Easymock cannot work with classes that are final which java.lang.Class is.
Related
I create a class named CAR and I also created an interface named car.
They both in a same source file. I make the CAR class implements the car interface and the IDE shows nothing wrong. But when I run this program, it gives an error that is
Exception in thread "main" java.lang.NoClassDefFoundError: test/car (wrong name: test/CAR)"
Why is that ? JAVA is not case sensitive, is it?
Here's the code:
package test;
interface car {
void changespeed(int x);
void changeoil(int x);
}
class CAR implements car {
private int speed;
private int oil;
public CAR(int _speed,int _oil) {
speed = _speed;
oil = _oil;
}
public void changespeed(int x) {
speed = x;
}
public void changeoil(int x) {
oil = x;
}
public void Show() {
System.out.printf(speed + " " + oil);
}
}
public class test {
public static void main (String[] args) {
CAR a = new CAR(100,200);
a.changespeed(200);
a.changeoil(200);
a.Show();
}
}
Technically, you can do this on some platforms.
It will work on Linux / UNIX
It will probably work on Mac OSX, though you may need to tweak things to turn of "user-friendly" case-insensitivity.
However, it is a bad idea to make your code-base dependent on the platform's ability to do case-sensitive pathname lookup. And it is also a bad idea to ignore the Java Style Conventions which clearly state that:
you should not define identifiers of the same kind that differ only in case,
you should always start a class name with an uppercase letter, and
all uppercase is reserved for constants.
The problem is that the standard Java mechanism for finding the file in which a class lives relies on being able to map the class name to a file name, on the assumption that filenames are case sensitive. If you follow the Java style guidelines, the mechanism works on all platforms. If you (wilfully) don't, you are going to be in for a world of pain ... and you won't get much sympathy.
(But if you managed to put your compiled classes into a JAR file with the correct casing for the class names, that should work even on Windows. Not sure of a good way to do that though ... if you are building on Windows.)
So, to answer your question:
why can't i use similar word as java class name and interface name which just case differs?
Because you are using Windows, and because you are ignoring Java style rules.
JAVA is not case sensitive, is it?
Yes it is.
I should also point out that Show() is a style violation, and so are changespeed(...), changeoil(...) and _speed, and _oil.
If you are writing code that only you will ever read, then you can (mostly) get away with ignoring style. But if you write code that other people will / might have to read, then you are liable to get a lot of criticism.
Java is case sensitive, it's the file-system that's causing you trouble. You'd better follow naming conventions.
Typically, compiling one .java file might give you multiple .class files. Basically each class in the source file goes into one .class file.
In your case, the compiler is trying to generate three files: car.class, CAR.class and test.class. In a file-system that treat CAR.class and car.class as the same file, you are going to have trouble. Similar issues arise when we try to unzip something created under a Linux system, where under the same folder there's two file names differ only in letter case.
Solution? Follow the naming convention. Basically you have to rename the interface or the class somehow:
interface Car {}
class MyCar implements Car {}
As #Luke Lee said, Windows files system is case insensitive.
If you compile your test.java program, it should makes class file named after their class name:
> javac test.java
CAR.class
car.class
test.class
but in Windows, CAR.class and car.class file names are considered as same file name.
So in run time, java.lang.NoClassDefFoundError occurs.
I am trying to load a class from a folder to check for the implementation of a specific method. The class has some imports that are not present in the folder or its subfolders. Loading the class with Class clazz = Class.forName(className, false, classLoader); works fine, but when I call clazz.getDeclaredMethod("methodName") then I get a NoClassDefFoundError because some imports cannot be resolved.
Is there a possibility to examine a class at runtime (I do not intend to call methods or instantiate it) without loading dependencies?
If not, how else can I check a class for a specific method implementation when I have a classes-folder as a starting point?
Interesting question.
I don't think you want to roll your own byte code parser, so try Apache BCEL or Spring ASM. Both allow you to read/write class files without having to load them.
You might be able to do that with a library such as Apache Commons BCEL.
The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).
you could try executing `javap ' from your program and parsing the output. For example:
javap Driver
Compiled from "Driver.java"
public class Driver {
public Driver();
public static void main(java.lang.String[]);
}
I've got a utility class that I've created:
package com.g2.quizification.utils;
import com.g2.quizification.domain.Question;
public class ParsingUtils {
public static Question parse(String raw) {
Question question = new Question();
//TODO: parse some stuff
return question;
}
}
...that lives here:
I've also followed the tutorials and created a testing app, that looks like this:
And here's my test code, just waiting for some good 'ole TDD:
package com.g2.quizification.utils.test;
import com.g2.quizification.domain.Question;
import com.g2.quizification.utils.ParsingUtils;
public class ParsingUtilsTest {
public void testParse() {
String raw = "Q:Question? A:Answer.";
Question question = ParsingUtils.parse(raw);
//assertEquals("Question?", question.getQuestion());
//assertEquals("Answer.", question.getAnswer());
}
}
The test class is obviously missing the extension, but all the examples seem to only show extending something like ActivityUnitTestCase. I'm not testing an activity; I just want to test a static method in a utility class. Is that possible?
It seems like creating a utility test class should be simple, but I'm not sure what the next step is and/or what I'm missing.
The best approach for test project is to add the test project so that its root directory tests/ is at the same level as the src/ directory of the main application's project. If you are using junit4 and eclipse, you can just right-click on the util class you want to test and choose New -> JUnit Test Case.
Basically I would expect a new test class named ParsingUtilTest under the source folder tests/ and within the package com.g2.quizification.utils.test. The test class should extend TestCase and each method you want to test in that util class should have a new method in the test class with the name preceded with "test". I mean to say, suppose you have a method name in ParsingUtils called parseXml. The test method name in ParsingUtilsTest (which Extend 'TestCase') should be named testParseXml
The test class is obviously missing the extension, but all the examples seem to only show extending something like ActivityUnitTestCase. I'm not testing an activity; I just want to test a static method in a utility class. Is that possible?
Yes, as long as the class your are testing has nothing to do with android apis. And if you do need to test code with android api dependencies, for example, testing a view or an activity, you might want to have a try with robolectric. It's faster than the ones that extend ActivityUnitTestCase.
I have been playing with robolectric a lot (to do TDD on android), and so far, I prefer version 1.1 or 1.2 to 2.x, more stable and run fast.
Besides the tools mentioned above, there are many practices for writing good test cases, naming conventions, code refactoring and such.
It seems like creating a utility test class should be simple, but I'm not sure what the next step is and/or what I'm missing.
Its good to begin with small steps, xUnit Test Patterns: Refactoring Test Code and Extreme Programming Explained are some good books for your reference.
So, I have something written in Java, and I want to extend it in Scala... The issue I'm running into is that Scala isn't seeing methods I need.
Here is how it's set up:
Player extends Mob, and Mob extends Entity.
I need to access a method in Player that isn't defined in Mob or Entity, but Scala doesn't think it exists even though Java does.
It can see methods defined by Mob and Entity just fine. Also, all the methods I'm talking about are non-static.
So, am I doing something wrong, or is this a limitation imposed by Scala?
Edit --
Here is the relevant code:
package test
import rsca.gs.model.Player
object Test {
def handle(p:Player): Unit = {
p.getActionSender().sendTeleBubble(0, 0, false);
}
}
Player class:
package rsca.gs.model;
// imports
public final class Player extends Mob {
// Implemented methods (not going to post them, as there are quite a few)
// Relevant code
private MiscPacketBuilder actionSender;
public MiscPacketBuilder getActionSender() {
return actionSender;
}
}
Error:
value getActionSender is not a member of rsca.gs.model.Player
I never encountered such problems, and you probably checked your configuration and everything else twice, so I would guess this is some Eclipse related build issue. You should try to build from the command line in order to see whether Scala or Eclipse is the problem.
Is it possible for you to run a test against the class just to see if you got the right one?
p.getClass.getMethods
... and if possible (may run into NPE) in order to find the source:
p.getClass.getProtectionDomain.getCodeSource.getLocation.getPath
When compiling the Scala class, do something like this:
scalac *.scala *.java
This way, Scala will look a the Java code to see what is available. If, however, the Java code is already compiled and provided as a jar file, just add it to the classpath used when compiling the Scala code.
I've come across an oddity of the JLS, or a JavaC bug (not sure which). Please read the following and provide an explanation, citing JLS passage or Sun Bug ID, as appropriate.
Suppose I have a contrived project with code in three "modules" -
API - defines the framework API - think Servlet API
Impl - defines the API implementation - think Tomcat Servlet container
App - the application I wrote
Here are the classes in each module:
API - MessagePrinter.java
package api;
public class MessagePrinter {
public void print(String message) {
System.out.println("MESSAGE: " + message);
}
}
API - MessageHolder.java (yes, it references an "impl" class - more on this later)
package api;
import impl.MessagePrinterInternal;
public class MessageHolder {
private final String message;
public MessageHolder(String message) {
this.message = message;
}
public void print(MessagePrinter printer) {
printer.print(message);
}
/**
* NOTE: Package-Private visibility.
*/
void print(MessagePrinterInternal printer) {
printer.print(message);
}
}
Impl - MessagePrinterInternal.java - This class depends on an API class. As the name suggests, it is intended for "internal" use elsewhere in my little framework.
package impl;
import api.MessagePrinter;
/**
* An "internal" class, not meant to be added to your
* application classpath. Think the Tomcat Servlet API implementation classes.
*/
public class MessagePrinterInternal extends MessagePrinter {
public void print(String message) {
System.out.println("INTERNAL: " + message);
}
}
Finally, the sole class in the App module...MyApp.java
import api.MessageHolder;
import api.MessagePrinter;
public class MyApp {
public static void main(String[] args) {
MessageHolder holder = new MessageHolder("Hope this compiles");
holder.print(new MessagePrinter());
}
}
So, now I attempt to compile my little application, MyApp.java. Suppose my API jars are exported via a jar, say api.jar, and being a good citizen I only referencd that jar in my classpath - not the Impl class shiped in impl.jar.
Now, obviously there is a flaw in my framework design in that the API classes shouldn't have any dependency on "internal" implementation classes. However, what came as a surprise is that MyApp.java didn't compile at all.
javac -cp api.jar src\MyApp.java
src\MyApp.java:11: cannot access impl.MessagePrinterInternal class file for impl.MessagePrinterInternal not found
holder.print(new MessagePrinter());
^
1 error
The problem is that the compiler is trying to resolve the version print() to use, due to method overloading. However, the compilation error is somewhat unexpected, as one of the methods is package-private, and therefore not visible to MyApp.
So, is this a javac bug, or some oddity of the JLS?
Compiler: Sun javac 1.6.0_14
There is is nothing wrong with JLS or javac. Of course this doesn't compile, because your class MessageHolder references MessagePrinterInternal which is not on the compile classpath if I understand your explanation right. You have to break this reference into the implementation, for example with an interface in your API.
EDIT 1: For clarification: This has nothing to do with the package-visible method as you seem to think. The problem is that the type MessagePrinterInternal is needed for compilation, but you don't have it on the classpath. You cannot expect javac to compile source code when it doesn't have access to referenced classes.
EDIT 2: I reread the code again and this is what seems to be happening: When MyApp is compiled, it tries to load class MessageHolder. Class MessageHolder references MessagePrinterInternal, so it tries to load that also and fails. I am not sure that is specified in the JLS, it might also depend on the JVM. In my experience with the Sun JVM, you need to have at least all statically referenced classes available when a class is loaded; that includes the types of fields, anything in the method signatures, extended classses and implemented interfaces. You could argue that this is counter-intuitive, but I would respond that in general there is very little you do with a class where such information is missing: you cannot instantiate objects, you cannot use the metadata (the Class object) etc. With that background knowledge, I would say the behavior you see is expected.
First off I would expect the things in the api package to be interfaces rather than classes (based on the name). Once you do this the problem will go away since you cannot have package access in interfaces.
The next thing is that, AFAIK, this is a Java oddity (in that it doesn't do what you would want). If you get rid of the public method and make the package on private you will get the same thing.
Changing everything in the api package to be interfaces will fix your problem and give you a cleaner separation in your code.
I guess you can always argue that javac can be a little bit smarter, but it has to stop somewhere. it's not human, human can always be smarter than a compiler, you can always find examples that make perfect sense for a human but dumbfound a compiler.
I don't know the exact spec on this matter, and I doubt javac authors made any mistake here. but who cares? why not put all dependencies in the classpath, even if some of them are superficial? doing that consistently makes our lives a lot easier.