Class: JavaClass::Classpath::TrackingClasspath

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/javaclass/classpath/tracking_classpath.rb

Overview

A delegator classpath that tracks which classes have been accessed. For an example see how to find (un)referenced JARs.

Author

Peter Kofler

Instance Method Summary collapse

Constructor Details

#initialize(classpath) ⇒ TrackingClasspath

Create a tracked instance of the classpath .



13
14
15
16
17
18
19
20
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 13

def initialize(classpath)
  unless classpath.respond_to?(:load_binary) || classpath.respond_to?(:load)  
    raise ArgumentError, "wrong type of delegatee #{classpath.class}"
  end
  @classpath = classpath
  reset_access
  super(classpath)
end

Instance Method Details

#accessed(classname = nil) ⇒ Object

Was the classname accessed then return the count? If classname is nil then check if any class was accessed.



68
69
70
71
72
73
74
75
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 68

def accessed(classname=nil)
  if classname
    key = to_key(classname)
    @accessed[key] 
  else
    @accessed.values.inject(0) {|s,e| s + e }
  end
end

#all_accessedObject

Return the classnames of all accessed classes. This is a list of frozen JavaClassFileName.



78
79
80
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 78

def all_accessed
  @accessed.keys.sort
end

#elementsObject

Returns the wrapped classpath element (self) of this decorated classpath.



23
24
25
26
27
28
29
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 23

def elements
  if [FolderClasspath, JarClasspath].include?(@classpath.class)
    [self]
  else
    @classpath.elements
  end
end

#load(classname) ⇒ Object

Read and disassemble the given class classname and mark as accessed.



44
45
46
47
48
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 44

def load(classname)
  key = to_key(classname)
  mark_accessed(key)
  @classpath.load(key)
end

#load_binary(classname) ⇒ Object

Load the binary and mark the classname as accessed.



37
38
39
40
41
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 37

def load_binary(classname)
  key = to_key(classname)
  mark_accessed(key)
  @classpath.load_binary(key)
end

#mark_accessed(classname) ⇒ Object

Mark the classname as accessed. Return the number of accesses so far.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 51

def mark_accessed(classname)
  key = to_key(classname)
  
  if @classpath.includes?(key)
    
    # hash keys need to be frozen to keep state
    if !@accessed.include?(key)
      key = key.freeze 
    end
    
    @accessed[key] += 1
  else
    nil
  end
end

#reset_accessObject

Reset all prior marked access.



32
33
34
# File 'lib/javaclass/classpath/tracking_classpath.rb', line 32

def reset_access
  @accessed = Hash.new(0) # class_file (JavaClassFileName) => cnt
end