using in C# vs. import in Java - java

I am coming from Java and C++ background. However, I am doing a C# application at the moment and one thing made me confused.
In Java when I import a package, it means I can access the classes that are placed in that package. For example, here I imported the ArrayList class from package java.util.
import java.util.ArrayList;
class ArrayListUtilization {
public static void main(String[] args) {
ArrayList<Integer> myList = new ArrayList<>(3);
myList.add(3);
myList.add(2);
myList.add(1);
System.out.println(myList);
}
}
Recently I had a problem in my c-sharp app, that I asked here. The funny part in my point of view is, when I added the following snippet of code:
var accountDbContext = services.GetRequiredService<AccountDbContext>();
accountDbContext.Database.EnsureCreated();
var accountDbCreator = accountDbContext.GetService<IRelationalDatabaseCreator>();
accountDbCreator.CreateTables();
I saw an error as following:
Error CS1929 'AccountDbContext' does not contain a definition for
'GetService' and the best extension method overload
'ServiceProviderServiceExtensions.GetService(IServiceProvider)'
requires a receiver of type 'IServiceProvider'
and from the error text, I understood accountDbContext object does not have GetService function. But when I press on show potential fixes, then it suggests me to add a using statement.
And it was the real fix. However, my question is what is the effect of this using statement on my object? The object is an instantiation of its class. How can adding a using statement effect on my object and add a function to it?

Note that what you are actually calling an extension method here:
accountDbContext.GetService<IRelationalDatabaseCreator>();
accountDbContext does not have a method called GetService. GetService is declared in AccessorExtensions, and the above line is just syntactic sugar for:
AccessorExtensions.GetService<IRelationalDatabaseCreator>(accountDbContext);
Now it should make sense that you need to add a using directive for the class in which the extension method is declared, in order to access the extension method.

Related

JavaCPP fails at function disambiguation

I am implementing a Java wrapper for a C++ project using JavaCPP. I have defined mappings for all custom types, but I'm struggling with a call to the std::sort_heap() function that takes a function as an argument.
This is the function call in the C++ code:
std::sort_heap(heap.begin(), heap.end(), comparePairs);
comparePairs is declared like this in this file:
bool comparePairs(
const std::pair<real, int32_t>& l,
const std::pair<real, int32_t>& r) {
return l.first > r.first;
}
When I try to run this with JavaCPP (using the JavaCPP Maven plugin), I get this error:
error: no matching function for call to ‘pop_heap(std::vector<std::pair<float, int> >::iterator, std::vector<std::pair<float, int> >::iterator, <unresolved overloaded function type>)’
std::pop_heap(heap.begin(), heap.end(), comparePairs);
^
Update: the problem seems to be due to the fact that another compairePairs() with a slightly different signature function is declared in another file. The C++ compiler disambiguates them fine, considering that each compairePairs() function is called only within the same file. However, JavaCPP seems to fail at that disambiguation somehow.
This is how the other type mappings are declared:
import org.bytedeco.javacpp.tools.Info;
import org.bytedeco.javacpp.tools.InfoMap;
import org.bytedeco.javacpp.tools.InfoMapper;
[...]
#Properties(value = #Platform(include = {[...]}), target = "[...]")
public class Wrapper implements InfoMapper {
public void map(InfoMap infoMap) {
infoMap.put(new Info("std::vector<std::string>").pointerTypes("StringVector").define())
// more put calls here
;
}
}
Question is thus: why does JavaCPP fail to disambiguate overloaded functions, and how can I fix it?
Note: the C++ code is a third party project, so changing the C++ code is not an option.
Update: the issues appears to be due to the compairPairs() function being declared twice in the C++ code (in two different files), with different signatures.
As described in the comment, wrapping the function call to comparePairs() into a lambda function resolves the issue.
See https://github.com/facebookresearch/fastText/pull/936/commits/cda295f1b5851df0a26a6ac2ab04230fb864a89d

Calling static method from another java class

I've recently switched from working in PHP to Java and have a query. Want to emphasise I'm a beginner in Java.
Essentially I am working in File A (with class A) and want to refer to a static method saved in File B (class B). Do I need to make any reference to File B when working with class A? (I'm thinking along the lines of require_once in PHP) My code in Class A is as follows:
Public class A{
String[] lists = B.staticMethod();
}
Eclipse is not recognising B as a class. Do I need to create an instance of B in order to access the static method. Feel like I'm really overlooking something and would appreciate any input.
Ensure you have proper access to B.staticMethod. Perhaps declare it as
public static String[] staticMethod() {
//code
}
Also, you need to import class B
import foo.bar.B; // use fully qualified path foo.bar.B
public class A {
String[] lists = B.staticMethod();
}
You don't need to create an instance of the class to call a static method, but you do need to import the class.
package foo;
//assuming B is in same package
import foo.B;
Public class A{
String[] lists = B.staticMethod();
}
Java has classloader mechanism that is kind of similar to PHP's autoloader. This means that you don't need anything like a include or require function: as long as the classes that you use are on the "classpath" they will be found.
Some people will say that you have to use the import statement. That's not true; import does nothing but give you a way to refer to classes with their short names, so that you don't have to repeat the package name every time.
For example, code in a program that works with the ArrayList and Date classes could be written like this:
java.util.ArrayList<java.util.Date> list = new java.util.ArrayList<>();
list.add(new java.util.Date());
Repeating the package name gets tiring after a while so we can use import to tell the compiler we want to refer to these classes by their short name:
import java.util.*;
....
ArrayList<Date> list = new ArrayList<>();
list.add(new Date());

attempting to get class names from a different package

Have got two projects javaapplication2 and javaapplication1. The same being their package names. In javaapplication2 ive imported javaapplication1 using
import javaapplication1.*;
i need to list all classses in the packeage. How to achieve this? I tried a simple code but it gets a null exception.
Package pck;
pck = Package.getPackage("javaapplication1");
System.out.println(pck.getClass());
I don't have enough rep to comment on this question or to mark it as such, but it is a duplicate of:
Getting all Classes from a Package
There are many good answers listed on that question - for instance the top is looking for classes that implement ICommand, so to implement this all you need to do is remove:
if (ICommand.class.isAssignableFrom(cls)) {
commands.add((Class<ICommand>) cls);
}
from the for loop and you have what you want.
I guess the jar containing package javaapplication1 is not in classpath as
Package.getPackage("javaapplication1");
is returning null for you.
Also,
You can have a look at the following link:
http://dzone.com/snippets/get-all-classes-within-package
or can explore the Reflection library from Google in order to get the required information, below is a sample code.
e.g.
Reflections reflections = new Reflections("javaapplication1");
Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);
If you go throgh the object class API it is written as:
//Object API
getClass
public final Class getClass()Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Returns:
the object of type Class that represents the runtime class of the object.
It's clearly written as it represents the run time class of an object.
Suppose if you have class called as "Helloworld" in side "javaapplication1" package
create object of the class as:
Helloworld world=new Helloworld();
and then try to run as
System.out.println(wolrld.getClass());
It will return the class path of current object.

Using BTrace to find when a class is created for the first time

I'm trying to use BTrace to find when a certain type is first instantiated in my program (Eclipse debugger isn't able to find it) as I'm seeing some strange behaviour (the Javolution XMLStreamWriterImpl is somehow adding elements to my XML before it should even have been created).
Anyway, I have the following method which I am using through JVisualVM, but nothing is showing up when running.
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
import java.lang.String;
#BTrace
public class ClassLoad {
#OnMethod(clazz = "javolution.xml.stream.XMLStreamWriterImpl", method = "<init>", location = #Location(value=Kind.NEW))
public static void site(#ProbeMethodName(fqn=true) String caller) {
println(strcat("Called from #", caller));
}
}
You need a different #OnMethod definition.
#OnMethod(clazz="/.*/", method="/.*/", location=#Location(value=Kind.NEW, clazz="javolution.xml.stream.XMLStreamWriterImpl"))
Basically you specify that you want to inspect all the methods of all the classes for occurrences of new javolution.xml.stream.XMLStreamWriterImpl instructions.
The rest of the code can stay the same.

Java or any other language: Which method/class invoked mine?

I would like to write a code internal to my method that print which method/class has invoked it.
(My assumption is that I can't change anything but my method..)
How about other programming languages?
EDIT: Thanks guys, how about JavaScript? python? C++?
This is specific to Java.
You can use Thread.currentThread().getStackTrace(). This will return an array of StackTraceElements.
The 2nd element in the array will be the calling method.
Example:
public void methodThatPrintsCaller() {
StackTraceElement elem = Thread.currentThread.getStackTrace()[2];
System.out.println(elem);
// rest of you code
}
If all you want to do is print out the stack trace and go hunting for the class, use
Thread.dumpStack();
See the API doc.
Justin has the general case down; I wanted to mention two special cases demonstrated by this snippit:
import java.util.Comparator;
public class WhoCalledMe {
public static void main(String[] args) {
((Comparator)(new SomeReifiedGeneric())).compare(null, null);
new WhoCalledMe().new SomeInnerClass().someInnerMethod();
}
public static StackTraceElement getCaller() {
//since it's a library function we use 3 instead of 2 to ignore ourself
return Thread.currentThread().getStackTrace()[3];
}
private void somePrivateMethod() {
System.out.println("somePrivateMethod() called by: " + WhoCalledMe.getCaller());
}
private class SomeInnerClass {
public void someInnerMethod() {
somePrivateMethod();
}
}
}
class SomeReifiedGeneric implements Comparator<SomeReifiedGeneric> {
public int compare(SomeReifiedGeneric o1, SomeReifiedGeneric o2) {
System.out.println("SomeRefiedGeneric.compare() called by: " + WhoCalledMe.getCaller());
return 0;
}
}
This prints:
SomeRefiedGeneric.compare() called by: SomeReifiedGeneric.compare(WhoCalledMe.java:1)
somePrivateMethod() called by: WhoCalledMe.access$0(WhoCalledMe.java:14)
Even though the first is called "directly" from main() and the second from SomeInnerClass.someInnerMethod(). These are two cases where there is a transparent call made in between the two methods.
In the first case, this is because we are calling the bridge method to a generic method, added by the compiler to ensure SomeReifiedGeneric can be used as a raw type.
In the second case, it is because we are calling a private member of WhoCalledMe from an inner class. To accomplish this, the compiler adds a synthetic method as a go-between to override the visibility problems.
the sequence of method calls is located in stack. this is how you get the stack: Get current stack trace in Java then get previous item.
Since you asked about other languages, Tcl gives you a command (info level) that lets you examine the call stack. For example, [info level -1] returns the caller of the current procedure, as well as the arguments used to call the current procedure.
In Python you use the inspect module.
Getting the function's name and file name is easy, as you see in the example below.
Getting the function itself is more work. I think you could use the __import__ function to import the caller's module. However you must somehow convert the filename to a valid module name.
import inspect
def find_caller():
caller_frame = inspect.currentframe().f_back
print "Called by function:", caller_frame.f_code.co_name
print "In file :", caller_frame.f_code.co_filename
#Alternative, probably more portable way
#print inspect.getframeinfo(caller_frame)
def foo():
find_caller()
foo()
Yes, it is possible.
Have a look at Thread.getStackTrace()
In Python, you should use the traceback or inspect modules. These will modules will shield you from the implementation details of the interpreter, which can differ even today (e.g. IronPython, Jython) and may change even more in the future. The way these modules do it under the standard Python interpreter today, however, is with sys._getframe(). In particular, sys._getframe(1).f_code.co_name provides the information you want.

Categories