Get Class Location from Class Object

Get class location from class object

For Methods and Procs Ruby 1.9 has method called source_location:

Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)

So you can request for the method:

m = Foo::Bar.method(:create)

And then ask for the source_location of that method:

m.source_location

This will return an array with filename and line number.
E.g for ActiveRecord::Base#validates this returns:

ActiveRecord::Base.method(:validates).source_location
# => ["/Users/laas/.rvm/gems/ruby-1.9.2-p0@arveaurik/gems/activemodel-3.2.2/lib/active_model/validations/validates.rb", 81]

For classes and modules, Ruby does not offer built in support, but there is an excellent Gist out there that builds upon source_location to return file for a given method or first file for a class if no method was specified:

  • ruby where_is module

EDIT: For Ruby 1.8.7 there is a gem that backports source_location:

  • ruby18_source_location

Find where java class is loaded from

Here's an example:

package foo;

public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}

This printed out:

file:/C:/Users/Jon/Test/foo/Test.class

How do I get the filepath for a class in Python?

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)

Getting filesystem path of class being executed

The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the parent to find the directory that the .jar is in.

How to find where a Python class is defined

You can use the inspect module to get the location where a module/package is defined.

inspect.getmodule(my_class)

Sample Output:

<module 'module_name' from '/path/to/my/module.py'>

As per the docs,

inspect.getmodule(object)

Try to guess which module an object was defined in.

How to get a Class Object from the Class Name in Java

You can use:

Class c = Class.forName("com.package.MyClass");

And later instantiate an object:

Object obj = c.newInstance();

EDIT: This is just the simplest use case. As indicated in the comments, you will need to consider constructor arguments and exceptions thrown by the initialization process. The JavaDocs for newInstance has all the details.



Related Topics



Leave a reply



Submit